I have a vector of a vector of pointers to a "TerrainCell" class as part of another "Mesh" class. This Mesh class basically holds the data for the terrain vertices and such for a chunk of a level. It has two major functions - InitializeMemory() and DeinitializeMemory(). It also has three main components - a width and height, and "mesh", which is:
std::vector<std::vector<TerrainCell*> > mesh;
I don't want to have to use up all the stack space. Anyways, "mesh" is supposed to have flat edges - the inner vectors should all have the same Size(). DeinitializeMemory() is supposed to delete all the pointers in mesh, and InitializeMemory() first calls DeinitializeMemory, then allocates new memory according to the width and height specified. Unfortunately, I made a simple memory-leak check, and it seems that the memory never gets deallocated. I was wondering how I am supposed to deallocate the memory in the vector successfully.
Here is the relevant code:
Mesh class declaration
//Declaration of TerrainCell (just a non-pointer array of 4 3d vertices)
#include "cell.h"
class Mesh
{
public:
Mesh();
Mesh(unsigned int init_width, unsigned int init_height);
~Mesh();
//Allocates memory for "mesh" according to "width" and "height"
void InitializeMemory();
//Deallocates all the memory in "mesh"
void DeinitializeMemory();
private:
//Terrain vertices
std::vector< std::vector<TerrainCell*> > mesh;
//height: the number of outer vectors for "mesh"
//width: the size of the inner vectors of "mesh"
unsigned int height, width;
};
InitializeMemory()
void Mesh::InitializeMemory()
{
DeinitializeMemory();
unsigned int i = 0;
for ( unsigned int out_count = 0; out_count < height; ++out_count )
{
std::vector<TerrainCell*> v_cells;
for ( unsigned int in_count = 0; in_count < width; ++in_count )
{
TerrainCell * t_cell = new TerrainCell;
v_cells.push_back(t_cell);
++i;
//Thought the lack of "delete t_cell" might be the cause of the
//memory leak. Leaving it in causes a double free error.
//delete t_cell;
}
mesh.push_back(v_cells);
}
}
DeinitializeMemory()
void Mesh::DeinitializeMemory()
{
//For each vector of vectors of TerrainCells
for ( std::vector<std::vector<TerrainCell*> >::iterator iter_out = mesh.begin();
iter_out != mesh.end();
++iter_out )
{
//Cycle through each cell in the vector
for ( std::vector<TerrainCell*>::iterator iter_in = (*iter_out).begin();
iter_in != (*iter_out).end();
++iter_in )
{
//And delete it... apparently unsuccessfully :(
delete (*iter_in);
}
//Clear the row (neccessary?)
(*iter_out).clear();
}
//Clear the mesh
mesh.clear();
}
Obviously, in a terrain editor, this is a very big problem :)
Thanks for any help you can provide.
[Edited by - silverphyre673 on June 5, 2005 8:45:28 PM]