Realloc on NULL-valued (or undefined) pointer

后端 未结 3 1036
天命终不由人
天命终不由人 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:08

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

    No, that would exactly be like a malloc.

    If instead of:

    int* ptr = NULL;
    

    I had this:

    int* ptr; // no value given to ptr
    

    would it be a problem to call realloc using ptr?

    Yes, there would be a problem. If realloc doesn't get a NULL, it will try to expand memory starting from that location, or may try to free and malloc another part of memory. Since uninitialized variables can have any value, chances are very high, they are not a value realloc likes. If you are lucky, your program would immediately crash.

提交回复
热议问题