This depends on what you want to do. realloc()
specifically is designed to take an existing allocation and change its size, preserving as much data as possible. Both examples you have provided are correct in the sense that they will compile, but they will do different things.
realloc(NULL, n)
is the same as malloc(n)
, so the second case is semantically equivalent to:
for(i = 0; i < n; i++){
myArray = (int *)malloc(i*sizeof(int));
free(myArray);
myArray = NULL;
}
In the first example, the data pointed to by myArray
will be retained. In the second example, the existing allocation will be thrown away and replaced with a brand new, uninitialized allocation. Any data pointed to by the original allocation will be discarded.
It should be noted that realloc()
will return NULL
if the allocation fails -- but if you passed it a non-NULL
pointer then that allocation will not have been freed. Passing one pointer into realloc()
and assigning the result directly into that same pointer variable can cause a memory leak if the reallocation fails, because the original allocation will still exist. The correct way to do this is to use a temporary pointer variable.