triclosan
triclosan

Reputation: 5714

Memory reallocation - keep my data in place

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

Answers (2)

gbjbaanb
gbjbaanb

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

user405725
user405725

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

Related Questions