Search code examples
cpointersnull-pointer

is doing (ptr && *ptr) good way to check whether any value assigned to the ptr? mine just keep crashing


Im not really sure that use of ptr&&(*ptr)
At first, I was not sure about is this for checking NULL ptr or existence of assigned value.
But now after running the code below I found that in both way it just doesnt work: runtime error occurred!

Can somebody explain what nasty thing inside is happening?
GCC 5.3.0

#include <stdio.h>
int main(void){
    int* ptr=NULL;
//    ptr=NULL;
    int res = (ptr && *ptr);

//assigning NULL to *ptr or ptr address results in runtime error. What's happening?
//compiled with gcc.exe (GCC) 5.3.0 on windows

    printf("address: %d \n val: %d \n",ptr,*ptr);
    printf("isNullptr? ptr&& *ptr %d",res);
    return;
}

Solution

  • Following line is completely ok, since short-circuiting prevents ptr from being dereferenced if it's equal to NULL.

    int res = (ptr && *ptr);
    

    But following code unconditionally dereferences it, leading to a crash.

    int* ptr=NULL;
    // ...
    printf("address: %p \n val: %d \n",(void *)ptr,*ptr);
    //                                             ^~~~
    

    Also, please note that a proper way to print a pointer is by using %p instead of %d, and the pointer has to be casted to void *. I've changed your printf() accordingly.