It depends on what you want to do. realloc() specifically designed to accept an existing distribution and resize it, storing as much data as possible. Both of the examples you provided are true in the sense that they will compile, but they will do different things.
realloc(NULL, n) same as malloc(n) , so the second case is semantically equivalent:
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 saved. In the second example, the existing distribution will be discarded and replaced with a new, uninitialized distribution. Any data indicated by the original distribution will be discarded.
It should be noted that realloc() will return NULL if the distribution fails, but if you passed it a pointer that is not NULL , then this distribution will not be freed. Passing one pointer to realloc() and assigning the result directly to the same pointer variable can lead to a memory leak if the redistribution fails, since the original distribution will still exist. The proper way to do this is to use a temporary pointer variable.
source share