MathieuGug
MathieuGug

Reputation: 77

Impossible to make a <list <list< int* > > work

I have quite a problem I can't solve despite the unreasonable amount of time I spent on. I'd like to have a list< list< int* > >, but it is not working. Here is my code :

int main(int argc, const char * argv[]) {
   int a=2;
   int b=3;

   list<list<int*>> test;

   list< list<int*> >::iterator it;
   it = test.begin();

   it->push_back(&a);
   it->push_back(&b);

   b=4; //should modify the content of "test"

   for(list <int*>::iterator it2 = it->begin(); it2 != it->end(); it2++) {
      cout << *it2 << endl;
   }
}

Using xCode, it compiles but I have a "Thread 1: EXC_BAD_ACCESS" error. I hope you will enlighten me !

Thank you !

Upvotes: 3

Views: 73

Answers (1)

Brian Bi
Brian Bi

Reputation: 119641

test is empty, so test.begin() is a singular iterator and it is illegal to dereference it. It causes undefined behaviour, similar to that from accessing an array out of bounds.

You need to do this:

test.emplace_back();
it = test.begin();

This will add a new value-initialized element to test, so it will become a one-element list containing a zero-element list. Then it will point to that single element.

Upvotes: 6

Related Questions