How to free memory allocation in C ++ dll in delphi application

I have a problem with mem highlight in c / c ++ dll and call it with delphi, sth like this:

create dll with c / c ++

#include "MemTestDll.h" extern "C" EXPORTAPI char* __cdecl Test() { char* str=new char[1024*1024*2]; return str; } 

then in delphi:

 function Test():PAnsiChar; cdecl; external 'MemTestDll.dll'; procedure TForm3.btn3Click(Sender: TObject); var ptr:PAnsiChar; begin ptr:=Test(); //FreeMem(ptr); // crash //SysFreeMem(ptr) //crash too end; 

I see the task manager, each click will lose 8 KB of memory.

  • How can i free ptr? FreeMem this pointer will crash the application

  • I allocate 1024 * 1024 * 2 bytes in a C / C ++ dll, why does it show an 8KB leak?

+4
source share
1 answer

The rule of using dynamic memory across the boundaries of a DLL is that the one who allocated the memory must also free it. You cannot allocate memory in a DLL and then free it outside of the DLL. Therefore, you must provide another function in your DLL that will free the pointer.

+7
source

Source: https://habr.com/ru/post/1497154/


All Articles