Reputation: 20790
Is there any problem to allocate memory in an application and free it in a function called from a dll/dylib?
But to allocate memory in a function from a dll/dylib and free it in the caller application?
Upvotes: 1
Views: 1694
Reputation: 47482
For a static library it is not generally a problem, but is usually not a good idea for dynamic libraries. Especially for libraries shared between projects.
The problem is you need to ensure that the memory allocation functions (new/delete, malloc/free) match exactly between your calling code and the dynamic library. For example, if you statically link the C-runtime with your executable, but the dynamic library is dynamically linked (or vice versa) then you have separate code running malloc for the executable vs the dynamic library.
To avoid any problems dynamic libraries will often expose their own alloc and free routines to guarantee consistency.
Upvotes: 6
Reputation: 958
No there's no fundamental problem in the sense it will work however the application which does the memory allocation must return a pointer which can then be passed to the DLL so that it can perform the delete (or free).
Of course both the application and the DLL must be using the same memory allocation as others point out otherwise chaos will ensue.
It's dangerous though and prone to error. In general it's better if the memory allocation and deallocation is handled in the same place and pointers passed to anything else which needs to access the allocated objects.
I did have this working for a C# library which called a DLL which allocated memory to return (large) results plus provided a delete method which was then called when the application had finished with them. It worked fine.
Upvotes: 2