Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using realloc in c

Tags:

c++

c

i am using void *realloc(void *pointer, size_t size); to increase the size of my pointer. how does realloc work?
does it create a nre address space, and copy the old value to the new address space and returns a pointer this address? or it just allocates more memory and binds it to the old one?

like image 363
lik Avatar asked Dec 15 '25 12:12

lik


1 Answers

@Iraklis has the right answer: it does the second (if it can get away with it) or the first (but only if it has to).

However, sometimes it can do neither, and will fail. Be careful: If it can't resize your data, it will return NULL, but the memory will NOT be freed. Code like this is wrong:

ptr = realloc(ptr, size);

If realloc returns NULL, the old ptr will never get freed because you've overwritten it with NULL. To do this properly you must do:

void *tmp = realloc(ptr, size);
if(tmp) ptr = tmp;
else /* handle error, often with: */ free(ptr);

On BSD systems, the above is turned into a library function called reallocf, which can be implemented as follows:

void *reallocf(void *p, size_t s)
{
    void *tmp = realloc(p, s);
    if(tmp) return tmp;
    free(p);
    return NULL;
}

Allowing you to safely use:

ptr = reallocf(ptr, size);

Note that if realloc has to allocate new space and copy the old data, it will free the old data. Only if it can't resize does it leave your data intact, in the event that a resize failure is a recoverable error.

like image 165
Chris Lutz Avatar answered Dec 17 '25 01:12

Chris Lutz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!