Is it required to free a pointer variable before using realloc?

c, malloc, memory-management, pointers

Solution

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();

Problem

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; } ```

Original source

Related problems