Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper usage of realloc()

Tags:

From man realloc:The realloc() function returns a pointer to the newly allocated memory, which is suitably aligned for any kind of variable and may be different from ptr, or NULL if the request fails.

So in this code snippet:

ptr = (int *) malloc(sizeof(int)); ptr1 = (int *) realloc(ptr, count * sizeof(int)); if(ptr1 == NULL){           //reallocated pointer ptr1     printf("Exiting!!\n");     free(ptr);     exit(0); }else{     free(ptr);          //to deallocate the previous memory block pointed by ptr so as not to leave orphaned blocks of memory when ptr=ptr1 executes and ptr moves on to another block     ptr = ptr1;         //deallocation using free has been done assuming that ptr and ptr1 do not point to the same address                      } 

Is it sufficient to just assume that the reallocated pointer points to a different block of memeory and not to the same block.Because if the assumption becomes false and realloc returns the address of the original memory block pointed to by ptr and then free(ptr) executes(for the reason given in the comments) then the memory block would be erased and the program would go nuts. Should I put in another condition which will compare the equality of ptr and ptr1 and exclude the execution of the free(ptr) statement?

like image 738
user3163420 Avatar asked Jan 08 '14 21:01

user3163420


People also ask

What does realloc () function do?

In the C Programming Language, the realloc function is used to resize a block of memory that was previously allocated. The realloc function allocates a block of memory (which be can make it larger or smaller in size than the original) and copies the contents of the old block to the new block of memory, if necessary.

How do I allocate memory with realloc?

Use of realloc() Size of dynamically allocated memory can be changed by using realloc(). As per the C99 standard: void * realloc ( void *ptr, size_t size); realloc deallocates the old object pointed to by ptr and returns a pointer to a new object that has the size specified by size.

What are the different uses of realloc function in C++?

C++ realloc() The realloc() function in C++ reallocates a block of memory that was previously allocated but not yet freed. The realloc() function reallocates memory that was previously allocated using malloc(), calloc() or realloc() function and yet not freed using the free() function.


1 Answers

Just don't call free() on your original ptr in the happy path. Essentially realloc() has done that for you.

ptr = malloc(sizeof(int)); ptr1 = realloc(ptr, count * sizeof(int)); if (ptr1 == NULL) // reallocated pointer ptr1 {            printf("\nExiting!!");     free(ptr);     exit(0); } else {     ptr = ptr1;           // the reallocation succeeded, we can overwrite our original pointer now } 
like image 189
Aaron S. Kurland Avatar answered Oct 20 '22 00:10

Aaron S. Kurland