ltheron
ltheron

Reputation: 301

Can't access to Object stored in multidimensional vector (C++)

I try to access to an object stored in a multidimensionnal vector :

It is an object of the class Case.

Carte::Carte(int x, int y) {
this->x = x;
this->y = y;
    for(int i; i<x; i++){
        carte.push_back(std::vector<Case*>());
        for(int j = 0; j<y; j++){
            Case aCase(i, j);
            carte[i].push_back(&aCase);
        }
    }
}

My Carte.h :

class Carte {
public:
Carte(int x, int y);
virtual ~Carte();
std::vector< std::vector<Case*> > carte;
int x,y;
};

Everything's fine but when I want to pass the object of Carte into the constructor on another class and try to read a variable of the class Case (Because there is objects of the class Case inside my vector) :

//I deleted the extra code...
Batiment::Batiment(Carte *carte) {
carte->carte[this->x][this->y]->libre = false;
}

This is my class Case :

class Case {
public:
Case(int x, int y);
virtual ~Case();
int x,y;
bool libre;
};

And when I execute, there is an "exit value = -1".

So I Debug, and it says :

Failed to execute MI command:
-data-evaluate-expression "(((('std::_Vector_base<Case*,std::allocator<Case*> >' *) this))->_M_impl)"
Error message from debugger back end:
Cannot access memory at address 0x78

There is no error during compilation but it seems I can't access to where the objects are in the vector...

Someone know why ?

Thank you.

Upvotes: 0

Views: 229

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409356

You push a pointer to a local variable, a variable which will go out of scope and be destructed before you use that pointer, leading you to dereference a stray pointer and you will get undefined behavior.

The code in question:

for(int j = 0; j<y; j++){
    Case aCase(i, j);
    carte[i].push_back(&aCase);
}

The object aCase will go out of scope and be destructed in the next iteration of the loop.

Upvotes: 1

Related Questions