Working on an app today, I discovered 2 things that I'd like to note down.

  • It's not necessary to check if a pointer is not nil before passing it to FreeMem. FreeMem checks if a pointer is not nil, before freeing it. Hence, FreeMem returns immediately if the passed pointer is nil.
  • It's not necessary for a pointer to be allocated before passing it to ReallocMem. If it's not allocated memory yet (ie, the pointer is nil), ReallocMem allocates memory to it.
Unfortunately, these checks are not documented.

So,

P := nil;
... Do some other stuff here...
FreeMem(P); // Even if you did not allocate memory previously, it's okay to call FreeMem(P), because FreeMem checks that P is not nil,  before proceeding further.

P := nil;
... Do some other stuff here...
ReallocMem(P, NewSize); // Even if P has not been allocated any memory, it's okay to call it, as ReallocMem will check to see if P is nil or not. If P is nil, then it allocates the memory. Otherwise, it'll expand the block of memory to the new size, and copy the existing data over to the newly allocated memory.