Name

SetMemoryManager Procedure

Syntax

procedure SetMemoryManager(const NewMgr: TMemoryManager);

Description

SetMemoryManager installs a new memory manager to handle dynamic memory allocations from GetMem, New, object creation, and all other needs for dynamic memory, including long strings, dynamic arrays, and Variants.

SetMemoryManager is a real procedure.

Tips and Tricks

  • When setting a new memory manager, the unit that calls SetMemoryManager must be the first unit in the project. If not, the first unit most likely allocates memory from Delphi’s default memory manager, but after your memory manager is installed, the new manager will be the one to free the memory even though it did not allocate that memory.

  • For the same reason, you should not save and restore the original memory manager. Delphi allocates memory at unpredictable times, and you cannot rely on the order of initializing and finalizing units to ensure that all memory allocated with one manager will be freed by the same manager. The only safe approach is to use one memory manager exclusively.

  • If you are using DLLs, you need to be careful about memory allocated by a DLL that is not freed before the DLL is unloaded. This can easily happen if you pass long strings, dynamic arrays, or Variants across DLL boundaries. The solution is to direct all dynamic memory requests to a separate DLL. Delphi’s ShareMem unit does this with borlndmm.dll, and you can do the same with your custom memory manager. See Chapter 2 for more information ...

Get Delphi in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.