0
votes

Assume following scenario:

  1. We allocate a block of memory using HeapAlloc() WINAPI function to var X

  2. We want to reallocate X using HeapRealloc()

  3. HeapRealloc() resizes the heap and moves to new location, therefore pointer has been changed - let's call it Y

Should we do HeapFree on the old memory address (X) after it has been moved by HeapReAlloc or will HeapReAlloc automatically clean up previous memory pointer for us?

1

1 Answers

3
votes

No. HeapReAlloc() will have already freed the old address. Virtually every allocator you'll come across does this, whether it's the Windows API heap functions or the standard C malloc()/realloc()/free(). Here's a direct quote from the HeapReAlloc() documentation, though, for good measure:

If HeapReAlloc fails, the original memory is not freed, and the original handle and pointer are still valid.

HeapReAlloc is guaranteed to preserve the content of the memory being reallocated, even if the new memory is allocated at a different location. The process of preserving the memory content involves a memory copy operation that is potentially very time-consuming.

These combined should lead to the conclusion that HeapReAlloc() frees the old memory address if successful.