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?

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top