I have a vector of pointers to class objects. These class objects invoke “new” as well to create an array.
I’m trying to avoid memory leaks, so I created a destructor which returns the object’s array back to freestore.
laboratory::~laboratory()
{
delete Users; // Users is an array from the heap
}
When I try to delete each element of the pointer vector, however, the program crashes:
for(int i = 0; i < vectorSize; i++)
delete labVector[i];
Any help is much appreciated.
Edit: Pasted code here: http://pastie.org/4168453
Class and function definitions are below main(). Sorry for pasting it this way, I was using a header file and 2 source files.
Well then that’s wrong. Should be
Anything you
newwith[]gets adeletewith[].On a side note; do you really need a vector of pointers here? It’s pretty darn rare to actually need that (though you see it a lot) and it completely negates the container’s ability to manage memory for you, requiring you to loop through and deallocate every element.
vectors use dynamic memory behind the scenes for each element. You could us a vector of smart pointers or even a
vector<vector<T>>(though, if performance is of the utmost concern, a jagged array may be a better choice. Don’t assume that though).