How `realloc` work actually in the background?

Ravindra Gupta picture Ravindra Gupta · Jan 29, 2014 · Viewed 8.7k times · Source

How realloc work actually in the background? If there is not enough memory available at old place does this one allocating two/many memory blocks and one pointer pointing to that and other are internally linked with each other or the old region copied into new place where enough memory is available and pointer is updating to new address and deleting the old memory?

And is that realloc is Compiler/OS dependent or independent?

Answer

Sergey L. picture Sergey L. · Jan 29, 2014

realloc attempts to extend your available memory range if sufficient memory is available behind it on the heap. If not then it is equivalent to malloc a block of the new size, memcpy your contents there, free the old block. This is independent of both OS and compiler and depends on the implementation of libc that you link against.

On a similar note: mremap/MREMAP_MAYMOVE (available on modern Linux) will attempt to extend your virtual mapping by the requested size. If that is not possible then it will move your mapping to a new virtual address that has sufficient VM space behind it and then extend your mapping. This is very fast if you are frequently resizing large mappings since no physical copying is done.