Reputation: 5714
Assuming I have some array in heap doesn't matter constructed by malloc
or new
. I need the most efficient way to enlarge it. I mean if it has enough free space which lying after already allocated data can I keep my data untouched. Is it possible to maintain in C++?
Does realloc
work in such manner?
Upvotes: 4
Views: 287
Reputation: 52659
yes, realloc works like that, though the link says that it is not guaranteed, I think this is for cases where memory is fragmented and there is not enough room to expand the memory block in-situ.
Upvotes: 1
Reputation:
Yes, realloc
is what you are looking for. Note that it won't work with new
, you will have to use malloc
(or, say, calloc
). Also, sometimes it is just impossible to extend memory, so realloc
will try to do it for you, but if it couldn't — it will resort to allocating new memory, copying your contents to a new place and freeing the old memory.
Upvotes: 3