I'm having trouble understanding some basic memory management principles in C++. This code is part of a loop that is part of a function that reads in a maze file into a 2D vector.
According to Valgrind, the following code is causing memory leaks...
Note that t is a MazeNode object and verts is a vector within the t class that holds pointers to node objects (not to be confused with MazeNode objects):
node* top = new node(TOP, rowCount, i, t.type); node* bot = new node(BOTTOM, rowCount, i, t.type); node* left = new node(LEFT, rowCount, i, t.type); node* right = new node(RIGHT, rowCount, i, t.type); t.verts.push_back(top); t.verts.push_back(bot); t.verts.push_back(left); t.verts.push_back(right); temp.push_back(t); top = NULL; bot = NULL; left = NULL; right = NULL; delete top; delete bot; delete left; delete right; Initially I did not set each of the pointers to NULL before deleting them, but would get allocation errors. So I just set them to NULL and my code works. I guess I'm just really confused why this would cause memory leaks and why I would need to set the pointers to NULL. There is probably a way easier non-pointer way to do this, but maybe this problem will help me understand memory management better.
Thanks everyone.
EDIT: Here's the MazeNode class (which is what 't' is) (also excuse my lazyness in writing this class, making everythign public like a struct)
class MazeNode { public: void setType(char c); char getChar(); NodeType type; vector<Direction> visitedFrom; vector<node*> verts; }; And the node class:
class node { public: node(); node(Direction d, int r, int c, NodeType t); ~node(); //empty definition node(const node* n); node& operator=(const node& n); void addAdj(node* a, int w); void printAdj() const; string direction() const; void print() const; bool operator<(const node& n) const; int distance; //from start bool visited; node* prev; vector<Edge> adj; Direction dir; int row, col; NodeType type; }; EDIT2: Thanks everyone. I understand the problem now. I changed my vectors of pointer objects so that I wasn't using pointers anymore.
tandtempvariables. I'm pretty sure that it's more than just setting to NULL that's causing the leak, but I need variable definitions to show what's "all" wrong here.new, don't usedelete. Those features of C++ are not suited for most code.