-4

I got a segmentation fault (core dumped) while runing my programm. The first version runs perfectly but i need the list as a pointer but then the code doesn't work anymore see second code. What am i doing wrong?

Runing version:

int main(int argc, char *argv[]) {

  std::list<int> TestList;
  for (int i = 0; i < 10; ++i) {
    TestList.push_back(i);
  }

  for (std::list<int>::const_iterator iterator = TestList.begin(), end = TestList.end(); iterator != end; ++iterator) {
    std::cout << *iterator << std::endl;
  }  

  return 0;
}

Not runing version:

int main(int argc, char *argv[]) {

      std::list<int> *TestList;
      for (int i = 0; i < 10; ++i) {
        TestList->push_back(i);
      }

      for (std::list<int>::const_iterator iterator = TestList->begin(), end = TestList->end(); iterator != end; ++iterator) {
        std::cout << *iterator << std::endl;
      }  

  return 0;
}    

BeiHerta
  • 73
  • 9

2 Answers2

1

In the second version TestList is just a pointer which doesn't point to any valid list objects. Try

std::list<int>* TestList = new std::list<int>();

Remember that you need to properly cleanup the heap allocated memory for the list too when you're done.

qutab
  • 307
  • 1
  • 5
  • 16
0

Second one cannot run since there is no list<int> object, but just a pointer pointing arbitary memory space.

If you want to use pointer, allocate memory area first.