Deleting Memory Allocated By DLL

Started by
3 comments, last by doctorsixstring 20 years, 6 months ago
In my project, I am using a DLL to store the game-specific code for my application. I have a function in my game object that returns a string wrapper class that I have created (mstring). /////////////////// mstring Game::GetTitle() { return "Game Title"; //creates an mstring object with the given string and returns it } /////////////////// In my main app, I use the GetTitle() function like this: Main::Run() { MessageBox(0,m_pGame->GetTitle().cstr(),0,0); } The cstr() function returns a char* pointer to the mstring''s string buffer. My problem occurs at the end of the Main::Run() function, where the mstring object created in Game::GetTitle() is deleted by the main app. So in other words, the DLL creates an mstring object and allocates space to store the string "Game Title". Then, the mstring object and its string buffer are deleted by the main program. This causes the app to crash. Now if I understand correctly, a DLL that is loaded by an EXE will use that program''s memory space. Thus, deleting memory allocated by DLL code from the main program should work fine. Unfortunately, it doesn''t. Any thoughts? -Mike
Advertisement
Any memory allocated by code within a dll should also be cleaned up by code within that dll. DLL_PROCESS_DETACH is a good place to do that. For reference, see Richter''s "Programming Applications".

"I thought what I'd do was, I'd pretend I was one of those deaf-mutes." - the Laughing Man
The problem with DLL''s on Windows is each DLL is linked against the C runtime. It is the C runtime that contains the memory/heap management.

So, even though the DLL is loaded into the address space of the EXE, each has its own seperate heap manager, which is where the problem is (this may not be 100% correct, but it is something like this, especially in debug mode).

You have two choices, import the malloc function from the .EXE, or delete any memory allocated by the DLL inside the DLL (using the STL across EXE/DLL boundaries is pretty much a no-no, unless certain precautions are taken).

Another common method is to use a virtual Release() member function of the object you are deleting which internally just delete''s itself [or decreases reference count if you want reference counting]. If you create the object in the DLL, its vtable element for release will be a pointer to the release member function in the DLL so the deallocation will work fine even if you call release from your separate executable.
Thanks for the info, guys. I kind of figured as much. I guess I will have to avoid returning temp objects like I was trying to do. This shouldn''t be a big deal, but if it is, I may go for something like what Polymorphic OOP said.

-Mike

This topic is closed to new replies.

Advertisement