Is it necessary to free memory before using realloc
again for a pointer variable. Which of the following is correct?
for(i = 0; i < n; i++){
myArray = (int *)realloc(myArray, i*sizeof(int));
}
for(i = 0; i < n; i++){
myArray = (int *)realloc(myArray, i*sizeof(int));
free(myArray);
myArray = NULL;
}
When reallocating the old pointer is invalidated and does not need to be freed manually. Only the last pointer after reallocating needs to be freed manually. The only exception to this is if realloc returns a null pointer. Only then is the old pointer still valid and still needs to be freed manually.
Description: The realloc() function allocates, reallocates, or frees the block of memory specified by old_blk based on the following rules: If old_blk is NULL, a new block of memory of size bytes is allocated. If the size is zero, the free() function is called to release the memory pointed to by old_blk.
If realloc succeeds, it will take ownership of the incoming memory (either manipulating it or free ing it) and return a pointer that can be used ("owned") by the calling function. If realloc fails (returns NULL ), your function retains ownership of the original memory and should free it when it's done with it.
It is safe to free a null pointer. The C Standard specifies that free(NULL) has no effect: The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs.
The specific usefulness of realloc
is that you don't need to free
before using it: it exists to grow memory that has already been allocated.
So it is not required and would be uncommon. When passed a NULL
pointer, realloc
behaves as malloc
. If you're using free
before calling it, you might as well be using malloc
.
Neither example is correct since you've omitted error handling. All the allocators can return NULL
and the usage of realloc
is a little tricky in this respect. Read the docs and examples carefully. Specifically, ptr = realloc(ptr, ...
is always a bad idea because if realloc
fails and returns NULL
, then you've just lost your reference and leaked memory. Instead use a tmp variable, e.g.:
tmp = realloc(ptr, newSize);
if (tmp != NULL)
ptr = tmp;
else handle_error();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With