Is the behavior implementation defined? If NULL and size == 0 are passed to realloc()
:
int main(void)
{
int *ptr = NULL;
ptr = realloc(ptr, 0);
if(ptr == NULL)
{
printf("realloc fails.\n");
goto Exit;
}
printf("Happy Scenario.\n");
Exit:
printf("Inside goto.\n");
return 0;
}
The above code should print "realloc fails", right? But it is not? I've read somewhere that this call to realloc
may return NULL also. When does that happen?
This behavior is implementation defined.
From the C standard:
Section 7.22.3.5 (realloc
):
3 If
ptr
is a null pointer, therealloc
function behaves like themalloc
function for the specified size. Otherwise, ifptr
does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to thefree
orrealloc
function, the behavior is undefined. If memory for the new object cannot be allocated, the old object is not deallocated and its value is unchanged.
So realloc(NULL, 0)
is the same as malloc(0)
If we then look at section 7.22.3.4 (malloc
):
2 The
malloc
function allocates space for an object whose size is specified bysize
and whose value is indeterminate.3 The
malloc
function returns either a null pointer or a pointer to the allocated space.
The standard does not state what happens when 0
is passed in.
But if you look at the Linux man page:
The
malloc()
function allocates size bytes and returns a pointer to the allocated memory. The memory is not initialized. If size is 0, thenmalloc()
returns either NULL, or a unique pointer value that can later be successfully passed tofree()
.
It explicitly states that the returned value can be freed but is not necessarily NULL.
In contrast, MSDN says:
If size is 0, malloc allocates a zero-length item in the heap and returns a valid pointer to that item. Always check the return from malloc, even if the amount of memory requested is small.
So for MSVC, you won't get a NULL pointer.
realloc(3) doc:
If ptr is NULL, then the call is equivalent to malloc(size), for all values of size
malloc(3) doc:
If size is 0, then malloc() returns either NULL, or a unique pointer value that can later be success‐fully passed to free().
So yes, it is implementation defined, you'll either get null or a pointer you can free.
The call
realloc(NULL, size);
is equivalent to
malloc(size);
And what malloc()
does when asked to allocate 0 bytes is a bit unclear, the standard doesn't say. I think it's implementation-defined. It basically "doesn't matter"; either it returns NULL
, or it returns a pointer where you can legally access zero bytes, those are pretty much alike. Both can be passed to free()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With