ReallocMemory
is a function. It returns the new pointer value; it does not modify its argument. You want to call ReallocMem
instead, or else use the result of the function:
ReallocMem(Node, SizeOf(Node^));
or
Node := ReallocMemory(Node, SizeOf(Node^));
When either of those functions cannot resize the block of memory in-place, it allocates new memory, copies the old contents into the new buffer, and then frees the original buffer. If you ignore the ReallocMemory
result, then you have discarded the new pointer and retained the old, stale pointer in the Node
variable. Continued use of a stale pointer would explain access violations and other unpredictable behavior.
There are two versions of those functions for C++ compatibility. C++ doesn't have Delphi's "compiler magic," which is what allows the compiler to have a single ReallocMem
function that accepts and modifies any pointer type.
The ReallocMemory
function looks like the C++ realloc
function, but they don't behave quite the same way, which is why it's safe to directly overwrite the input variable with the function's return value. When reallocation fails, the function throws an exception, just like ReallocMem
, where as realloc
just returns a null pointer.