Realloc on NULL-valued (or undefined) pointer

后端 未结 3 1031
天命终不由人
天命终不由人 2020-12-09 07:35

I was reading about realloc and got confused about a point mentioned there. Consider the code below:

#include 
#include 

int          


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-09 08:18

    Is there any danger in allocating memory with realloc using the initially NULL-valued ptr

    None

    7.22.3.5

    If ptr is a null pointer, the realloc function behaves like the malloc function for the specified size.

    For the second part:

    int* ptr; // no value given to ptr
    

    would it be a problem to call realloc using ptr?

    If you're using uninitialized pointers then that is a very serious problem indeed since you can't predict what their value will be. The function realloc only works correctly for NULL or values obtained from malloc / realloc.

    Otherwise, if ptr does not match a pointer earlier returned by a memory management function [...] the behavior is undefined

提交回复
热议问题