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?
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?
No, it's not guaranteed.
For example, what if you run this (evil) code prior to your example:
That maps an anonymous page with read/write permissions at address
0
.A segfault is not guaranteed by the C standard.
Dereferencing an invalid pointer invokes undefined behavior.
No, the program is not guaranteed to segfault. Dereferencing a pointer to which an invalid value has been assigned is undefined behaviour, and the standard clearly says that undefined behaviour imposes no requirements. It may terminate program execution but it does not have to; it may even ignore the situation completely:
In a word, no.
To quote from Wikipedia:
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 :)
You do not have any guarantee; dereferencing a null pointer is undefined behavior. It will probably result in a segfault, unless you have certain optimizations turned on or are compiling on a weird platform, in which case it might start executing some other function with effectively random arguments, generate some other error, grab some value out of memory, or make demons fly out of your nose, or skip that line entirely. The only one of those which I’d even be surprised by is the next-to-last.
In more detail:
NULL
, decide “that isn’t allowed, so that code path can never happen”, and get rid of the usual function cleanup code; this would result in your program sliding into whatever function happens to be next in the output binary.If for some reason you want to generate a segfault, a much better way to do that is with
(after including the appropriate headers). This sends the segfault signal without any actual segmentation violation. If you do want to actually commit a segmentation violation, you’re best bet is to map and then unmap some page (this is OS-dependent) and then try to access a pointer into that page.