Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
}
like image 765
stressed_geek Avatar asked Jul 18 '12 19:07

stressed_geek


People also ask

Do I need to free old pointer after realloc?

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.

Does realloc free the pointer?

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.

Does realloc automatically free memory?

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.

Do you need to free a pointer to NULL in C?

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.


1 Answers

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();
like image 153
pb2q Avatar answered Sep 22 '22 03:09

pb2q