xetra11 xetra11 - 2 months ago 7
C++ Question

Is a NULL pointer's dereference also equals NULL?

Does the following snippet compile/execute the block in the if-statement?

int* pointer = NULL;
int deref = *pointer;
if(deref == NULL){
// will execute?
}


Since the
pointer
variable contains NULL does the dereference of this pointer variable also return NULL or will this result in a runtime error?

Answer

The result is undefined, which means literally anything can happen. Undefined doesn't mean crash and it doesn't mean (as many people think) implementation specific. It means anything and maybe something different every time can happen.

In Linux, where the typical result of dereferencing a NULL pointer is a segmentation fault.

If you compile the code on GCC(Linux),

#include <stdio.h>

int main()
{
    int* pointer = NULL;
    int deref = *pointer;
    if(deref == NULL)
    {
        // will execute?
    }
}

You see this warning:

warning: comparison between pointer and integer [enabled by default]
 if(deref == NULL){
          ^

And If you run the program, you see the Segmentation fault (core dumped).