cif-statementreallocnegation

Negation of a void pointer Realloc


I was reading a C code, and I didn't understand well a line :

str = realloc(NULL, sizeof(*str)*size);//size is start size
    if(!str)return str;

what does the !str mean ?

The code read an input string from a user then realloc dynamically the memory.


Solution

  • A pointer in C is "falsy" if it is a null pointer, and "truthy" otherwise.

    So if (!str) return str; means that if str is NULL (meaning that the allocation failed) the function returns str (i.e. NULL). It could also be written as if (str == NULL) return str;.