Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to release memory allocate in c++ dll in delphi application

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

create a 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 taskmanager,each click will leak 8 KB memory.

  1. How can i release ptr? FreeMem this pointer will crash the application

  2. I allocate 1024*1024*2 bytes in C/C++ dll,why it shows leak 8KB?

like image 353
Haozes Avatar asked Mar 23 '23 18:03

Haozes


1 Answers

The rule for using dynamic memory across DLL boundaries is that whoever allocated the memory must also free it. You cannot allocate memory in the DLL and then free it outside the DLL. So you should provide another function in your DLL that will free a pointer.

like image 86
paddy Avatar answered Apr 07 '23 18:04

paddy