Deleting memory from DLLs (C++)

Started by
4 comments, last by arunvb 19 years, 4 months ago
I have recently starting moving alot of code i have worked on into DLLs, and have come across this problem i cant seem to fix - i have a class which is instanciated with 'new' inside a function in the DLL and passed to the main program. When i attempt to delete the object in the application (not in the dll) the program crashes with an assertion error immediately after the destructor function is finished. This doesnt happen if the object is deleted from within the DLL, or if it is created outside of the DLL. Can someone please explain why this happens, and if possible a workaround - i dont want to have to track every instance to see if it was created by the DLL or EXE... Thanks
Advertisement
First question: are both the DLL and the EXE built against a DLL version of the C-runtime libraries? If not, change that and try again. This doesn't fix all the problems you can run into that fits under you description, but does solve 80% of them.
You have to release memory allocated in a Dll in the DLL it was allocated in, its all about the heapspace they use and stuff. No workaround other than changing your code, but it shouldnt be a problem to have a 'Destroy' function or memebr of the class for each object you allocate.
to Anon: Thanks. Ok, i thought that might be the problem (something to do with the exe 'owning' the memory?). So im just going to have to force the EXE to use the DLL to both 'new' and 'delete' the class instances... That sucks.
To SiCrane: Im just using the default settings that Visual Studio gives for a W32 Exe and a W32 Dynamic Library.
When you have static linking between the exe and dll, they maintain seperate heaps and I believe only, the owner of the heap can allocate or delete memory from the heap. That's why you need the new and delete to be executed from the same module.

That's not the case though if you dynamically link the dll with the exe (using the LoadLibrary at runtime) since in this case both the exe and the dll share the same heap. In this scenario you should not be having problems if you have the new and delete across module boundaries.

This topic is closed to new replies.

Advertisement