取消引用空指针(C/C ++)时可以保证segfault [英] Is segfault guaranteed when dereferencing null pointer (C/C++)
问题描述
在下面的C/C ++代码中
In the C/C++ code below
int * a = malloc(N * sizeof(int)); // suppose return value is NULL
a[2] = 1;
在malloc返回 NULL
的情况下,我是否保证将发生segfault或行为不可预测?
In the case where malloc returns NULL
, do I have a guarantee that segfault will occur or is the behavior unpredictable?
推荐答案
总之,没有.
要引用 Wikipedia :
取消引用NULL指针通常会导致尝试读取或从未映射的内存中写入-触发分段故障或访问冲突.这可能代表开发者自己导致程序崩溃或被转化为异常抓住.但是,在某些情况下,这不是情况.例如,在x86实模式下,地址0000:0000为可读且通常可写,因此取消引用空指针是完全有效但通常不受欢迎的动作,可能会导致应用程序中未定义但不会崩溃的行为.另请注意在某些情况下,有意取消引用NULL是有意的且定义明确;例如用C编写的16位BIOS代码实模式x86设备可以将IDT写入设备的物理地址0通过取消引用NULL指针进行写入来创建计算机.这也是编译器可以优化
NULL
指针取消引用,避免出现分段错误,但会导致其他意外情况行为 ...
Dereferencing the NULL pointer typically results in an attempted read or write from memory that is not mapped - triggering a segmentation fault or access violation. This may represent itself to the developer as a program crash, or be transformed into an exception that can be caught. There are, however, certain circumstances where this is not the case. For example, in x86-real mode, the address 0000:0000 is readable and usually writable, hence dereferencing the null pointer is a perfectly valid but typically unwanted action that may lead to undefined but non-crashing behaviour in the application. Note also that there are occasions when dereferencing the NULL is intentional and well defined; for example BIOS code written in C for 16-bit real-mode x86 devices may write the IDT at physical address 0 of the machine by dereferencing a NULL pointer for writing. It is also possible for the compiler to optimize away the
NULL
pointer dereference, avoiding a segmentation fault but causing other undesired behavior...
在C中,取消引用空指针的行为是未定义.
In C, the behavior of dereferencing a null pointer is undefined.
还要查看此取消引用的空类指针的野生示例,但仍然可以正常工作.
Also check out this wild example of a null class pointer dereferenced, but which still works just fine.
基本上,不要这样做,但随后您知道了:)
Basically, don't do this, but then you knew that :)
这篇关于取消引用空指针(C/C ++)时可以保证segfault的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!