What if NULL and size 0 are passed to realloc()?

依然范特西╮ 提交于 2021-02-19 01:18:51

问题


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?


回答1:


This behavior is implementation defined.

From the C standard:

Section 7.22.3.5 (realloc):

3 If ptr is a null pointer, the realloc function behaves like the malloc function for the specified size. Otherwise, if ptr does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to the free or realloc 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 by size 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, then malloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().

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.




回答2:


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.




回答3:


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().



来源:https://stackoverflow.com/questions/42302696/what-if-null-and-size-0-are-passed-to-realloc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!