views:

50

answers:

2

What is the right and best way to reallocate memory? for example I allocate 100 bytes with WinAPI function HeapAlloc then I fill 100 bytes of that memory with some data and now I want to add more new data at end of previous...

What Should I do? Make a new allocation with more bytes and then copy old+new to new location and free old memory? Or there is some way to allocate new memory at end of old data and then copy only new data?

+2  A: 

You should probably use HeapReAlloc since Windows will no doubt have optimisations in place if it can just expand the memory without copying data.

For example, I've seen implementations of realloc (the C standard one) which checks to see if the current block can just absorb a free block following it. If so, it does that to avoid a copy operation. If not, it allocates the new memory and does the copy before freeing the old.

Another advantage of that is that you minimise the extra memory required. In a copy version, you have to have two copies of the current data in existence at some point.

paxdiablo
Thanks, now I'm going to try it :)
davispuh
+1  A: 

HeapReAlloc?

Andreas Rejbrand