Reputation: 21
I'm having trouble with my exercise here - I want to know about the realloc function a bit more -
If we send a pointer to the realloc, and it fails to allocate memory [returns null] does the memory that used to be allocated, now deallocated? although we failed?
ePointer = (Element*)realloc(stack->content, (sizeof(Element) * capacityOfStack(stack) * 2));
when stack->content
being the pointer ofcourse, if we failed now have ePointer
as NULL
, then stack->content
is no longer allocated?
Thanks alot!!
Upvotes: 0
Views: 337
Reputation: 1430
realloc()
does not de-allocate before trying to allocate again. What it does is first try to allocate a new block. If it fails, it returns and the old pointer is still valid. If it succeeds, then it copies the content from the original block into the new block, and then calls free()
on the original block.
Upvotes: 0
Reputation: 386706
From man 3 realloc
If
realloc()
fails, the original block is left untouched; it is not freed or moved.
Upvotes: 1
Reputation: 61398
stack->content
is still valid. If realloc
fails, it returns NULL, but the old block of memory remains valid, that's the interface.
https://en.cppreference.com/w/c/memory/realloc
Upvotes: 2
Reputation:
From the man
page for realloc
:
For realloc(), the input pointer is still valid if reallocation failed.
Upvotes: 3