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?
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.
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.
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.
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 }
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