用C解引用指针为0 [英] Dereferencing a pointer to 0 in C

查看:202
本文介绍了用C解引用指针为0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时到内存地址0x0数据是很有价值 - 以86实模式IVT作为更被誉为例子:它开始于0x0和包含指向中断处理程序:在一个0x00的DWORD是零错误处理程序的指针来划分的。

Sometimes data at memory address 0x0 is quite valuable -- take x86 real mode IVT as a more known example: it starts at 0x0 and contains pointers to interrupt handlers: a dword at 0x00 is a pointer to division by zero error handler.

不过,C11语言标准禁止解引用空指针 [WG14 N1570 6.5.3.2],它被定义为初始化为0指针或指针,空指针的 [WG14 N1570 的6.3.2.3],有效地禁止的第一字节。

However, C11 language standard prohibits dereferencing null pointers [WG14 N1570 6.5.3.2], which are defined as pointers initialized with 0 or pointers initialized with a null pointer [WG14 N1570 6.3.2.3], effectively banning the very first byte.

如何在需要时人们实际使用为0x0?

How do people actually use 0x0 when it's needed?

推荐答案

C没有的禁止的解引用空指针,它只是使未定义的行为。

C does not prohibit dereferencing the null pointer, it merely makes it undefined behavior.

如果你的环境是这样的,你能够解引用包含地址为0x0 指针,那么你应该能够做到这一点。 C语言标准也不说,当你这样做会发生什么。 (在大多数环境中,结果将是一个程序崩溃。)

If your environment is such that you're able to dereference a pointer containing the address 0x0, then you should be able to do so. The C language standard says nothing about what will happen when you do so. (And in most environments, the result will be a program crash.)

一个具体的例子(如果我记得正确此):在基于68K-3太阳计算机,提领一空指针并没有导致陷阱;相反,OS存储在存储器地址零零值,以及解引用空指针(其指向地址零)将产生零值。这意味着,例如,一个C程序可以治疗一个空指针作为一个有效的指针为空字符串。一些软件,有意或无意,依赖于这种行为。软件移植到基于Sun SPARC的4,它被困在空指针引用时,这需要清理很大。 (我清楚地记得阅读有关这一点,但我无法找到一个参考,我会更新,如果我能找到它。)

A concrete example (if I'm remembering this correctly): On the 68k-based Sun 3 computers, dereferencing a null pointer did not cause a trap; instead, the OS stored a zero value at memory address zero, and dereferencing a null pointer (which pointed to address zero) would yield that zero value. That meant, for example, that a C program could treat a null pointer as a valid pointer to an empty string. Some software, intentionally or not, depended on this behavior. This required a great deal of cleanup when porting software to the SPARC-based Sun 4, which trapped on null pointer dereferences. (I distinctly remember reading about this, but I was unable to find a reference; I'll update this if I can find it.)

请注意,该空指针的的必然解决为零;更precisely,一个空的重新presentation可以是或可以不是所有位零。它非常普遍的,但它不能保证。 (如果不是,那么整数到指针转换的(无效*)0 是不平凡的。)

Note that the null pointer is not necessarily address zero; more precisely, the representation of a null may or may not be all-bits-zero. It very commonly is, but it's not guaranteed. (If it's not, then the integer-to-pointer conversion of (void*)0 is non-trivial.)

comp.lang.c常见问题解答第5节讨论空指针。

这篇关于用C解引用指针为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆