Reallocation of memory - keep my data in place

Assuming I have some array on the heap does not matter built using malloc or new . I need the most efficient way to expand it. I mean, if he has enough free space that lies after the data already allocated, I can keep my data intact. Is it possible to support in C ++?

Does realloc this way?

+4
source share
2 answers

Yes, realloc is what you are looking for. Note that this will not work with new , you will need to use malloc (or, say, calloc ). In addition, sometimes it is simply impossible to expand the memory, so realloc will try to do it for you, but if it does not succeed, it will resort to allocating new memory, copying your contents to a new location and freeing up old memory.

+3
source

yes, realloc works like this, although the link says that it is not guaranteed, I think this applies to cases where the memory is fragmented and there is not enough space to expand the in-situ memory block.

+1
source

All Articles