Skip to main content
gamedev.net
🔒 Locked

memory problems with dll

Started by fatima Jun 11, 2010 at 9:19 AM 6 replies 1.3k views
Original Post
fatima
fatima
I am using the following method to export my classes to a dll.
__declspec(dllexport) myclass
{
//
};
without any additional task(creating *.def files,etc...).
usually everything works well except releasing memory.
can you explain the correct way for allocating and releasing memory in dlls?
I have tried many ways, butt all of them failed.
sorry for my english.thanks in advance.
Zipster
Zipster
The fail-proof approach is to always release memory in the same DLL it was allocated in. This is because every module that links against the runtime statically gets its own copy of the runtime, meaning that its runtime state is going to be unique to itself. Any allocations/releases you perform in that module aren't going to be reflected anywhere else, so its crucial that anything allocated there is also release there. On the other hand, if everything links against the runtime dynamically they'll all share the same runtime state, so you have more freedom with regard to where memory is allocated and released. However the first approach handles the most restrictive case so should be preferred (especially since you can't always control the linkage of every module you're using).
fatima
fatima
thanks.I understand this.
please check those:

myclass *object = 0;//a pointer in application
Create(&object); //a function defined in dll;
DoWork(object); // a function defined in application;
ReleaseThisObject(object);//a function defined in dll;

I think this is what I have to do.Is this the correct way?
(but I have checked that already).
Zipster
Zipster
Yes, as long as your allocate/release are in the same module, everything should be fine regardless of how your runtime is linked.
Sneftel
Sneftel
Quote:
Original post by fatima
I think this is what I have to do.Is this the correct way?

It is. A common, idiomatic method of ensuring this is to have classes with private constructors and destructors, and make Create() and Destroy() member functions. (The former, of course, needs to be a static member function.) Or, even better, have Create() return a shared_ptr to the object; because of how shared_ptr is implemented, deletion will be handled properly no matter where the last reference disappears from.
fatima
fatima
thank you again.
fatima
fatima
and what is shared_ptr?
Sneftel
Sneftel
It's a pointer that handles its own deletion for you. more info

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.