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.
CodePudding user response:
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;
.
CodePudding user response:
This if statement
if(!str)return str;
is equivalent to
if( str == NULL )return str;
or
if( str == 0 )return str;
That is it means that if the memory was not allocated (the function realloc
returned a null pointer) then this null pointer is returned from the function that calls realloc
.
From the C Standard (6.5.3.3 Unary arithmetic operators)
5 The result of the logical negation operator ! is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0. The result has type int. The expression !E is equivalent to (0==E).
Instead of calling realloc
str = realloc(NULL, sizeof(*str)*size);
you could call the function malloc
with the same result
str = malloc( sizeof( *str ) * size );
To indeed reallocate memory the first parameter in its call should be a non null pointer. Otherwise realloc
behaves as malloc
.
CodePudding user response:
The !
operator evaluates to 1 if its argument is equal to 0 and evaluates to 0 if it is not.
So !str
is exactly equivalent to str==0
, and comparing a pointer to 0 is the same as comparing it to NULL, so it is the same as str==NULL
.