Archived

This topic is now archived and is closed to further replies.

gibber

Fixing Memory Leaks

Recommended Posts

I saw over on www.flipcode.com the other day how to trap memory leaks in MSVC. Great fun. I''ve spent the day fixing the millions of memory leaks in my game (Which is now far more stable as a result . Now ive narrowed it down to a few pointers that i cannot free() for some reason. Most of them are double pointers(pointer to pointer) thus.... float **pfloats; pfloats = (float **)malloc(sizeof(float*)); for (i=0 to numberofloats-1) pfloats = (float *)malloc(sizeof(float)); GameLoop() playwithfloats() for (i=0 to numberofloats-1) free(pfloats[i]); free(pFloats) However. The way i attempt to free this data doesnt work. The memory leak remains, and in some circumstances i get an error saying that the memory block is not valid.

Share this post


Link to post
Share on other sites
My first reaction was that you had a few typos in the code you posted. Just in case you don't have any types, here's what I see
The line:
pfloats = (float **)malloc(sizeof(float*));
Only ever allocates memory for one float*, regardless of numberoffloats. And your loop to allocate floats is always allocating to the same variable, pfloat. What I believe you either meant to type, or should do is something more like this:
  
float** pfloats;
pfloats = (float**)malloc( sizeof(float*)*numberoffloats );

for( i=0; i<numberoffloat; i++ )
pfloats[i] = (float*)malloc( sizeof(float) );

GameLoop().
...

for( i=0; i<numberoffloats; i++ )
free( pfloats[i] );

free( pfloats );


And from this it appears that you only need a simple array of floats, which brings up the suggestion of just using one malloc/free like so:

  
float* pfloats;
pfloats = (float*)malloc( sizeof(float)*numberoffloats );

GameLoop();
...

free( pfloats );


Hope this helps
Jason


Edited by - jassmith on October 31, 2001 4:50:54 PM

Share this post


Link to post
Share on other sites
Yes, i rushed that message. It should have read...

float **pfloats;
pfloats = (float **)malloc(sizeof(float*)*numberofloats);

for (i=0 to numberofloats-1)
pfloats = (float *)malloc(sizeof(float));

GameLoop()
playwithfloats()

for (i=0 to numberofloats-1)
free(pfloats[i]);
free(pFloats);

It does appear that i only need an array of floats. But i am abstracting alot here. The real class uses a struct for a particle that has two "banks" of pointers to these structs.

struct tParticle **Used;
struct tParticle **Unused;

By switching pointers between these two i have a list of used particles (should be draw) and unused particles (ready for re-use by a Add() function).

It all works right, i just get memory leaks because im not freeing these ** (double pointers, or pointer to pointer) properly.

Share this post


Link to post
Share on other sites