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
SetMemoryManagermust 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’sShareMemunit does this with borlndmm.dll, and you can do the same with your custom memory manager. See Chapter 2 for more information ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access