Realloc on NULL-valued (or undefined) pointer

user1607425 picture user1607425 · Aug 27, 2012 · Viewed 23.7k times · Source

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

#include <stdio.h>
#include <stdlib.h>

int main () {

    int* ptr = NULL;
    ptr = realloc(ptr, 10*sizeof(int));
    return 0;
}

Is there any danger in allocating memory with realloc using the initially NULL-valued ptr? 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?

Answer

cnicutar picture cnicutar · Aug 27, 2012

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