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;
}
The specific usefulness of
reallocis that you don’t need tofreebefore using it: it exists to grow memory that has already been allocated.So it is not required and would be uncommon. When passed a
NULLpointer,reallocbehaves asmalloc. If you’re usingfreebefore calling it, you might as well be usingmalloc.Neither example is correct since you’ve omitted error handling. All the allocators can return
NULLand the usage ofreallocis a little tricky in this respect. Read the docs and examples carefully. Specifically,ptr = realloc(ptr, ...is always a bad idea because ifreallocfails and returnsNULL, then you’ve just lost your reference and leaked memory. Instead use a tmp variable, e.g.: