Memory leak in delete loop
"You have some memory leaks in the end due to a logical error in your deletion loop."
My 开发者_StackOverflow社区friend said this and I don't see it.
for(int i=0; i<nrOfAvailableSeats; i++)
{
delete passengers[i];
}
delete [] passengers;
You start with nrOfAvailableSeats
set to initial value (100), then over the program runtime it might decrement (since you have
nrOfAvailableSeats--;
in your code) and so when you use it in your loop you won't delete
some of the objects.
At the very least you have to define a global constant:
const int PlaneCapacity = 100;
and use it to initialize nrOfAvailableSeats
and in both the array creation and deletion loops.
Its because you delete array of passengers after deleting only some of its elements.
So when you do delete [] passengers;
some ( [i], [i+1], ... ) elements may stay undeleted.
In linked file there is code: nrOfAvailableSeats--;
And when you free your data you mignt have memleak because nrOfAvailableSeats
can be < 100
You initialized all available seats to 0/null,thus, in the cleanup phase, just iterate over all the 100 elements and delete each item. (Edit: checking for null pointer prior to delete is redundant, nevermind that.)
Alternatively use a std::vector if you are allowed to use the STL. Then just iterate through the vector and delete them all, since you will only have so much items in the vector as you actually use them. (If you only work with push and pop).
To delete something from a vector that is in use (not about to be completely emptied), is to swap the item you want to delete with vector.back()
, then delete vector.back()
and then pop_back()
.
Note: this invalidates any iterators, you'll have to re-assign them properly, or in the case of only one item you wished to delete, just break out of the iteration loop, via break
or return
.
#include "Passenger.h"
#include "EconomyClass.h"
#include "FirstClass.h"
#include <vector>
int main()
{
std::vector<Passenger*> passengers
//add passengers the vector grows when needed, it does so by copying the items, which, in the
//case of raw pointers like this, fast.
passengers.push_back(new FirstClass(name, purpose, chair));
passengers.push_back(new EconomyClass(name, purpose, food));
//delete all, starting from the back of the stack
//check the std::vector reference online for details
std::vector<Passenger*>::reverse_iterator start,end;
start = passengers.rbegin();
end = passengers.rend();
//iterate through all items, in this case, 2
for(;start!=end;++start)
{
delete *start;
}
//optional since it would get called on cleanup anyway)
passengers.clear();
}
精彩评论