c++cnullnullptr

Difference Between NULL and Zero in Comparing


I know a little bit about NULL, but when it comes to comparing I get confused.
For Example:

int* p;
if(p == NULL){
//do stuff
}
if(p == 0){
//do stuff
}

In the first comparison "p" compares with what address?

Is it looking for the reference point of "p", and seeing if it is valid or not?


Solution

  • In every modern implementation of C, NULL is zero, usually as a pointer value:

    #define  NULL  (void *) 0
    

    So comparing, say, a character to NULL is likely to be invalid:

    char ch = 'a';
    if (ch == NULL)     //  probably "invalid comparison of pointer with scalar"
    

    As a pointer value, NULL chosen to point to invalid memory so that dereferencing it (on a suitable architecture) will cause a memory fault. Most virtual machines reserve lower memory just for this purpose and implemented by leaving low memory unmapped to physical memory. How much memory is unreserved? Could be a few kilobytes, but many implementations reserve a few megabytes.