Alex Rivera | Logout

Memory leaks - the horror of every programmer?

Asked 2011-02-06T15:27:18.017
21

I'm programming a game engine in C++, which also has Lua support.

My biggest horror: Memory leaks.

It's not like my game is already infested with them, I'm rather afraid of them popping out of the ground like mushrooms, when the development is in a late phase and the project huge and complex.

I'm afraid of them because they seem extremely hard to spot for me. Especially in sophisticated systems. If my engine is almost finished, the game runs and the memory gets eaten away, what will I do? Where will I start searching?

  • Is my fear of memory leaks justified?
  • How can one find out where a memory leak lies?
  • Aren't there good tools which help in finding the source of memory leaks today?
Edit
Report

3 Answers

2

At least for the Lua part you can use your own memory allocator and track all allocations and freeing and so spot any memory leaks.

answered 2011-02-06T23:34:03.087
1

There are various techniques to track memory leaks.

The simplest is to use a macro and a specific allocator that would store the function that allocated this. That way, you could track each allocation and see which aren't deleted when they should be. Then you can start writing unittest and assert that memory has been freed.

If you use pre-compiled containers all the time, this won't work as all allocations will be in containers. Then your options are:

  • Use a thread-local-value to identify the subsystem or class id (in debug builds) that's running, so that your allocator can detect who is allocating memory. You could even use a stack to track memory usage hierarchially in your engine.
  • Actually retrieve the call stack and store that, if your compiler has sufficient support.
  • Use memory pools for the subsystems, and measure if their size increases disproportionately. (This is also a (admittedly poor) workaround for leaky memory, since you could free the entire pool at once, thus freeing leaked memory too, if you're able.)
  • On Windows, there are some macros that track memory allocation by source line automatically under debug builds.

There are probably more options than that. Testing and the use of a custom global new/delete override (that can be queried) should prove useful, if your design permits it.

Also, see the Electronic Arts STL C++ paper for some discussion on what needs to be done in STL/C++ to support proper game development. (It's probably a bit more hardcore than your engine, but it certainly contains many nuggets of inspiration and ingenuity.)

answered 2011-02-06T22:20:46.583
1

How can one find out where a memory leak lies?

Visual Leak Detector for Visual C++ 2008/2010

answered 2011-03-05T12:57:21.653

Your Answer