Browse  Forum  Clubs  Chat  News 

Game Developers Club -> Tutorials -> [Advanced] Basic and helpfull memory leak protection (C )

Tutorials Forum: [Advanced] Basic and helpfull memory leak protection (C )

GhostManZero: [Advanced] Basic and helpfull memory leak protection (C ) - Jul 13th 2006, 7:44PM Link | Report
Usually whenever anyone starts working with dynamic memory (new, delete, malloc, realloc, free) they may have problems with memory leaks (memory allocated (new, malloc, realloc) that is never freed), which makes the programs you write unstable. I will show a basic, yet helpfull templated class (in C because C doesnt support templates nor classes) that takes care of allocating memory and deallocating it to make sure it is always freed. I shall start writing the C code:


template<typename vartype> //We want any kind of variable
class MemoryContainer
{
private:
bool Allocated,AllocatedArray; //We will need to know if we have allocated anything, and if we did if we allocated a array or just a normal variable
vartype *p; //The pointer to the variable
void Free() //free our allocated variable
{
if(Allocated && p) //If we allocated it, and p is still valid
{
if(AllocatedArray) //if we allocated a array
{
delete [] p; //free our array
}
else
{
delete p; //else free our variable
};
}
Allocated = AllocatedArray = 0; //So we dont do this more than once
p = NULL; //Set p to 0
};
public:
MemoryContainer() //Here we reset everything
{
p = NULL;
Allocated = AllocatedArray = 0;
};
vartype *GetPointer() //To get the data allocated in memry
{
return p;
};
void Allocate(unsigned int Size) //here we allocate the same type of variable multiplyed by Size (so if we want 3 ints we just call allocate with 3 as Size
{
Free(); //If something was allocated, free it
if(Size > 1) //If the total elements we want are bigger than 1 we are allocating a array
{
Allocated = AllocatedArray = true;
};
p = new vartype[Size]; //Allocate
if(!p) //If we failed allocating reset everything
{
Allocated = AllocatedArray = 0;
p = NULL;
};
}
~MemoryContainer() //When the object is destroyed, free the memory
{
Free();
};
};


This code may not be perfect, but it does the job. Now you dont need to free your memry manually. This will be a great help for anyone using dynamic memory.
GhostManZero - Jul 13th 2006, 7:45PM Link | Report
C plus plus wont appear as a C with 2 ' ' =/
Page: