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
?
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