Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning char buffer from DLL function in C without producing memory leak

I have to write a DLL in C containing a function that returns a specific string (as a pointer to a char buffer representing the string). The function in the DLL will be invoked repeatedly and will execute in different threads.

The right thing to do would be to allocate the char buffer in the function and to free the allocated buffer in a caller environment after the returning buffer was used.

// DLL function

char *getString() {
    char *buffer = (char *)malloc(STRING_LEN);
    // fill buffer with some string
    return buffer;
}

Unfortunately, the programming environment that will call the function in my dll has no mechanism to free the returning buffer, therefore causing a memory leak.

How to return a string in the situation like this without producing a memory leak?

like image 869
id001 Avatar asked Oct 25 '25 13:10

id001


1 Answers

DLLs use a separate heap, so what gets allocated in a dll must be deallocated by that same dll.

As hmjd said, one option is to return the buffer back to the DLL that gave it to you for it to delete it. So the dll provides a deallocation function.

Your other option, that I like better - is for the calling program to provide the memory itself. E.g. you allocate the buffer in calling program and pass it in, including the length of the buffer, and have the dll function fail with the required length if the buffer isn't big enough. Like this:

bool doStuff( char* buffer, int& len )
{
    if ( len < tooSmall() )
    {
       len = requiredLength();
       return false;
    }

    // fill the buffer here somehow

    return true;
}

Then you can manage the buffer in the calling program as normal. One advantage of this is that is it easy for the calling program to re-use the buffer if it makes sense.

like image 86
Rafael Baptista Avatar answered Oct 27 '25 03:10

Rafael Baptista