In the C/C++ code below
int * a = malloc(N * sizeof(int)); // suppose return value is NULL
a[2] = 1;
In the case where malloc returns NULL
, do I have a guarantee that segfault will occur or is the behavior unpredictable?
Dereferencing a null pointer always results in undefined behavior and can cause crashes. If the compiler finds a pointer dereference, it treats that pointer as nonnull. As a result, the optimizer may remove null equality checks for dereferenced pointers.
If the program dereferences the null pointer, it can cause a segmentation fault or other undefined behavior, which can lead to a crash.
In practice, dereferencing a null pointer may result in an attempted read or write from memory that is not mapped, triggering a segmentation fault or memory access violation. This may manifest itself as a program crash, or be transformed into a software exception that can be caught by program code.
Dereferencing a null pointer is undefined behavior, typically abnormal program termination. In some situations, however, dereferencing a null pointer can lead to the execution of arbitrary code [Jack 2007, van Sprundel 2006].
In a word, no.
To quote from Wikipedia:
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...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 :)
A segfault is not guaranteed by the C standard.
Dereferencing an invalid pointer invokes undefined behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With