Mega Code Archive

 
Categories / Delphi / Examples
 

Memory lost and found and released

Roy Nelson was astonished to find that lots of Delphi-written DLLs were regularly leaking memory: after tracking down the cause, he set to work finding a workable plug to what turned out to be a rather difficult leak. This article has been long in the making: it all started about two years ago, after a conversation with a previous colleague. The conversation centred on the fact that they were experiencing problems with their ISAPI DLLs written in Delphi. It seemed as if the DLLs were leaking 4Kb of memory every time they were loaded into memory. Eventually they switched over to CGI to fix the problem. My reaction was ‘What? My Delphi losing memory? Never!’ I did not investigate this any further at that time. However, about two months ago I saw someone mention a ‘known’ leak in the VCL on a newsgroup. I was intrigued, as the magic 4Kb number was mentioned. Everyone seemed to know about this, and even what was causing the leak. What was going on here? I then had a look at the code and I saw why it had not been plugged. This leak in Delphi DLLs exhibits itself only under specific conditions. The most important condition is that the Controls unit has to be referenced somewhere in the units used to compile the DLL. Secondly, the DLL must not make use of packages. Lastly, the DLL has to be explicitly loaded and unloaded using the LoadLibraryXX and FreeLibrary API calls.