I have tried freeing memory without using free()
as below
int *ptr = malloc(20);
realloc(ptr, 0);
Will it work?
I have tried freeing memory without using free()
as below
int *ptr = malloc(20);
realloc(ptr, 0);
Will it work?
C language standards differ on this one: in C90 passing zero size was the same as calling free
:
If size is zero, the memory previously allocated at ptr is deallocated as if a call to free was made, and a null pointer is returned.
However, this changed in C99:
If size is zero, the return value depends on the particular library implementation: it may either be a null pointer or some other location that shall not be dereferenced.
Note that freeing is no longer a requirement; neither is returning a NULL
when zero size is passed.
realloc(ptr, 0)
is not equivalent to free(ptr)
The standard C11
says:
If the size of the space requested is zero, the behavior is implementation-defined: either a null pointer is returned, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object.
Why because realloc
does below things,
Maybe, but you can't count on it. From the docs:
If new_size is zero, the behavior is implementation defined (null pointer may be returned, or some non-null pointer may be returned that may not be used to access storage).
At least for POSIX: realloc(p, 0)
is not the same as free(p)
.
From the current POSIX documentation on realloc()
:
Previous versions explicitly permitted a call to realloc (p, 0) to free the space pointed to by p and return a null pointer. While this behavior could be interpreted as permitted by this version of the standard, the C language committee have indicated that this interpretation is incorrect.