i'm trying to free an apartment class object properly, but valgrind says "invalid free, address...is on thread 1's stack" Here's the code: I'll be very grateful if you could point to my mistakes.
class Apartment{
public:
enum SquareType {EMPTY, WALL, NUM_SQUARE_TYPES};
class ApartmentException : public std::exception {};
class IllegalArgException : public ApartmentException {};
class OutOfApartmentBoundsException : public ApartmentException {};
int length;
int width;
int price;
SquareType** squares;
Apartment (SquareType** squares, int length, int width, int price);
Apartment (const Apartment& apartment);
Apartment& operator=(const Apartment& apartment);
~Apartment();
};
Apartment::Apartment (SquareType** squares=NULL, int length=0, int width=0, int price=0){
this->price=price;
this->length=length;
this->width=width;
this->squares = new SquareType*[length];
for(int i=0; i<length ; i++){
this->squares[i]= new SquareType[width];
}
this->squares = squares;
for(int i=0; i<length; i++){
for(int j=0; j<width; j++){
this->squares[i][j] = squares[i][j];
}
}
}
Apartment::Apartment (const Apartment& apartment):length(apartment.length),
width(apartment.width),price(apartment.price),squares(apartment.squares){
for(int i=0; i<apartment.length; i++){
for(int j=0; j<apartment.width; j++){
squares[i][j] = apartment.squares[i][j];
}
}
}
Apartment& Apartment::operator=(const Apartment& apartment){
if(this == &apartment){
return *this;
}
for(int i=0;i<length;i++){
delete [] squares[i];
}
delete [] squares;
squares = new SquareType*[apartment.length];
for(int i=0; i<apartment.length ; i++){
squares[i]= new SquareType[apartment.width];
}
for(int i=0; i<apartment.length; i++){
for(int j=0; j<apartment.width; j++){
squares[i][j] = apartment.squares[i][j];
}
}
price=apartment.price;
length=apartment.length;
width=apartment.width;
return *this;
}
Apartment::~Apartment(){
for(int i=0;i<length;i++){
delete [] squares[i];
}
delete [] squares;
}
that's the main:
int main(){
Apartment::SquareType square1[5]={Apartment::WALL};
Apartment::SquareType square2[5]={Apartment::WALL};
Apartment::SquareType square3[5]={Apartment::WALL};
Apartment::SquareType square4[5]={Apartment::WALL};
Apartment::SquareType* squares[4]={square1,square2,square3,square4};
Apartment::SquareType* Squares[3]={square1,square2,square3};
Apartment ap(squares,4,5,0);
Apartment ap2(Squares,3,5,50);
return 0;
}
and that's the valgrind output:valg