0

I'm trying to figure out why dereferencing the empty list iterator is preventing the rest of the code from running. Comment out the line and everything seems fine, but leave it in and the program doesn't seem to get past that point.

I guess it's supposed to be an error since the list is empty, but I'm not getting any warnings or errors.

I'm using codeblocks with MinGW

    std::list<std::string> slist;
    std::string word;

    auto iter = slist.begin();

    //what is this doing?
    std::cout << (*iter) << std::endl;

    while(std::cin >> word)
    {
        iter = slist.insert(iter, word);
    }

    slist.insert(slist.begin(), {"foo", "bar"});
    for(auto item: slist)
        std::cout << item << std::endl;
Chandra Shekhar
  • 598
  • 1
  • 7
  • 25
ebmadrio
  • 13
  • 1
  • 4
  • 5
    It's undefined behavior. Anything can happen. – Lukas-T May 10 '20 at 10:58
  • 1
    *but I'm not getting any warnings or errors.* -- Maybe in a debug build that has iterator checking, such as Visual Studio, you will get an error. But otherwise, C++ does not check and the behavior is undefined. – PaulMcKenzie May 10 '20 at 11:05
  • 1
    If `slist` is an empty list, its `begin()` iterator is equivalent to an `end()` iterator. Dereferencing an end iterator (better named as "past the end") gives undefined behaviour. `list` is a library type, so the compiler cannot predict its behaviour (such as what its contents are) that is determined at run time. – Peter May 10 '20 at 11:08
  • https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior – M.M May 10 '20 at 11:19
  • https://en.cppreference.com/w/cpp/language/ub also read the articles linked at the bottom. – Jesper Juhl May 10 '20 at 12:48

1 Answers1

2

Well std::list is empty! De-referencing means you are attempting to use something that is not defined. It is just wrong. You should definitely not do that.

You should do instead

for (auto i : slist)
   std::cout << i << std::endl;

which is safe.

Dhaval Taunk
  • 1,662
  • 1
  • 9
  • 17
stackoverblown
  • 734
  • 5
  • 10