[SDL] ot - memory leaks

Christer Sandberg christer.sandberg at mdh.se
Fri Aug 3 03:15:20 PDT 2007


On Thursdayen den 2 August 2007, neil at cloudsprinter.com wrote:
>would there be some kinda valgrind windows cygwin combination or is that
> just too wierd and crazy?
There is a memory debugger named Fortify
http://www.geocities.com/SiliconValley/Horizon/8596/fortify.html
Beside it can tell you memory leaks it's also capable to trap many memory 
violations. It's source based so you can use it on either system. Back in bad 
old days when I was on DOS I used it a lot and was satisfied with it.

To avoid memory leaks and memory violations you should focus on documenting 
and a clean program structure. If a function returns a pointer to memory that 
it has allocated, then always mention that in a comment:
/* ... returns a pointer to a blah that the caller is responsible for... */
And similarly for members in structs:
struct BAR {
  /* Points to a FOO. The memory is owned by this BAR. */
  FOO *foo;
  /* Points to another FOO. The memory is NOT owned by this BAR. */
  FOO *foo2;
...
Also make separate functions to destroy your objects (and here you can make 
use of you carefully typed comments):
destroy_bar(BAR *bar)
{
  ...
  destroy_foo(foo);
  free(bar);
}

This way you can track where things come from and who owns them when the 
memory debugger tells you that you have a leak.

Moving to C++ you basically have to do the same. Using STL may sometimes help 
you, but if you put pointers into the containers you must be aware of the 
leak problem anyway. Using references instead of pointers in C++ may also 
help you, but it's not likely that you can live entirely without pointers in 
C++.
-- 
Christer


More information about the SDL mailing list