I am trying to create a C-style DLL interface that takes in an input char * and assigns an output char * after performing some translation operation. The return value of the function is an error code, so it won’t be used to return a char *.
I call the function in this manner:
char* output;
myfunc((char *) input.c_str(), &output);
And the function is defined as:
DLL_EXPORT int myfunc(char* input, char** output)
{
string translation = translate(input);
*output = (char *) malloc((translation.length()+1)*sizeof(char));
strcpy(*output,(char *) translation.c_str());
}
Is this a correct way of implementing this? Am I creating a memory leak?
It’s correct, but you also need to provide another DLL function that will free the memory. You cannot assume that the executable which has loaded your DLL is using the same version of the C runtime library, so if it tries to call
freeon the returned memory, you might end up corrupting your heap due to differences in themalloc/freeimplementations in the different runtimes.Your API should look something like this:
See also allocating and freeing memory across module boundaries.