realloc
is used to reallocate the memory dynamically.
Suppose I have allocated 7 bytes using the malloc
function and now I want to extend it to 30 bytes.
What will happen in the background if there is no sequential (continously in a single row) space of 30 bytes in the memory?
Is there any error or will memory be allocated in parts?
No, the data will be copied for you into the new block that the returned p points at, before the old block is freed. This all happens before realloc returns, so the new p points to your data still.
Because the new block can be in a new memory location, the pointer returned by realloc is not guaranteed to be the pointer passed through the memblock argument. realloc does not zero newly allocated memory in the case of buffer growth.
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.
The realloc function changes the size of the block whose address is ptr to be newsize . Since the space after the end of the block may be in use, realloc may find it necessary to copy the block to a new address where more free space is available. The value of realloc is the new address of the block.
realloc
works behind the scenes roughly like this:
NULL
.So, you can test for failure by testing for NULL
, but be aware that you don't overwrite the old pointer too early:
int* p = malloc(x);
/* ... */
p = realloc(p, y); /* WRONG: Old pointer lost if realloc fails: memory leak! */
/* Correct way: */
{
int* temp = realloc(p, y);
if (NULL == temp)
{
/* Handle error; p is still valid */
}
else
{
/* p now possibly points to deallocated memory. Overwrite it with the pointer
to the new block, to start using that */
p = temp;
}
}
realloc
will only succeed if it can return a contiguous ("sequential" in your words) block of memory. If no such block exists, it will return NULL
.
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