C Memory

Mike Parker aldacron at gmail.com
Sun May 12 07:06:45 PDT 2013


On Sunday, 12 May 2013 at 10:11:57 UTC, Namespace wrote:
> I get the error, although I don't call any unload method (or 
> quit any SDL component) and although I recompiled derelict3, 
> where I comment out all static (shared) DTor's.
> Maybe the only solution would be (as you said) to transfer all 
> deallocations into a terminate method, but that is no opinion 
> for me (and would cause a growing memory, if the game runs a 
> long time). And I want to use RAII. So I must live with this 
> invalid memory error.

I think you need to reconsider your use-case for RAII here. 
Wanting to use it is fine, but letting these errors persist just 
so you can do so is not something I would recommend.

What you are missing here is that there's no such thing as that 
this "(and would cause a growing memory, if the game runs a long 
time)" is an issue you are likely to run into by using D's class 
destructors to handle resource deallocation (as I mentioned in a 
previous post), but not with the system I describe here.

You're misunderstanding the purpose of the terminate call. It's 
there not to release all the memory your app ever uses, but to 
clean up any resources /still hanging around/ at shutdown. You 
need to pay special attention to memory management when 
developing a game. RAII isn't going to help you with D's classes, 
but you can still get a comfortable system in place that keeps 
deallocations localized in specific places, allowing you to free 
as few or as many resources as you want. You're likely already 
using some sort of manager structure for most of your game 
systems anyway. Even in a simple Asteroids game you'd have a list 
of Sprites that are active. That list becomes your record of 
resources that need to be deallocated. So just add one function 
that does that, make sure it's called at shutdown, and now you've 
avoided this error you're having. By going with this approach, 
you can have exact control over when resources are released and 
in what order. That should always be an overriding goal in game 
development.

I promise you, this will save you a lot of headaches down the 
road by eliminating a whole class of potential memory-related 
bugs (and they will pop up eventually) and code maintenance 
costs. One of the side-effects of mixing memory managed by the GC 
with that allocated outside of the GC is that you have to be 
responsible for the latter.


More information about the Digitalmars-d-learn mailing list