4

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?

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Is the rule of windows dll or delphi rule? When i use c++ call a c/c++ dll, delete that pointer in caller,that's ok. I don't know the size i should allocate in caller,so i must free it in caller
This is a fundamental rule of using DLLs anywhere
Haozes: you can get away with that if you have a shared memory manager. But it's a bad idea, since someone else might import your dll and not use the memory manager. This is why, for example, a lot of windows API calls take a buffer and the buffer size as parameters. You're saying "tell me this, put the answer into this chunk of memory I allocated for you". Most of those, if you set the size to zero, will return the size they need.
In theory it should be possible for the dll to use an OS API call for allocating the memory which could then be released by the application using the corresponding OS call to free the memory. Usually this isn't what happens, though, because all programming languages come with their built in memory managers which add another layer on top of the OS API calls and the dlls use them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.