3

I am experiencing the following behavior: I create a map, do a find on the key and delete the map entry. After erase, I print the elements using the iterator and I expected it to dump core but it works.

Why does it work?

     typedef std::pair<std::string, int> pair;
    std::map<pair, int> nameidCntMap;

    pair pair1("ABC", 139812);
    pair pair2("XYZ", 139915);
    pair pair3("PQR", 139098);


    nameidCntMap.insert(std::make_pair(pair1, 1));
    nameidCntMap.insert(std::make_pair(pair2, 1));
    nameidCntMap.insert(std::make_pair(pair3, 1));

    std::map<pair, int>::iterator it = nameidCntMap.find(pair1);
    if (it != nameidCntMap.end())
    {
            symsrcidCntMap.erase(it);
   
            std::cout<<"Pair::first: "<<it->first.first << "Pair::second: "<<it->first.second<<"map second:"<<it->second<<std::endl;
    }
halfer
  • 19,824
  • 17
  • 99
  • 186
Winjun
  • 31
  • 1
  • 6
    Using `it` once it's no longer valid invokes undefined behavior. A core dump is a possible outcome, but anything could happen, including printing the values. – cigien Nov 19 '20 at 05:34
  • Does this answer your question? [Can a local variable's memory be accessed outside its scope?](https://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope) – Kostas Nov 19 '20 at 05:40
  • 1
    If a C++ program was required to detect all errors and dump core when they occur then such a program would run much slower. You could design a language like this (Java for instance) but C++ chooses to prefer speed over safety. – john Nov 19 '20 at 06:48
  • @john But does Java do that (in case like this). It would happily remove the item from the container but it would remain valid (as we still have a pointer to the object). – Martin York Nov 26 '20 at 01:03
  • @john "Much slower." And the understatement award for the week goes to... you. :) – 3Dave Nov 26 '20 at 01:16
  • Undefined behaviour doesn't just make it do what you expect (dumping code) or doing what the program says (printing the values). If can also mean deleting your hard drive, downloading malware or anything else. As an example, read this https://devblogs.microsoft.com/oldnewthing/20140627-00/?p=633 – Jerry Jeremiah Nov 26 '20 at 01:25

1 Answers1

4

Why does it work?

It doesn't "work".

Behaviour of the program is undefined.

expected it to dump core

Your expectation is misguided. The program isn't defined to "dump core" when you indirect through an invalid iterator. No behaviour is defined for such program. As such, any behaviour is possible. Among all possible behaviours, there is the possibility that the behaviour is what you didn't expect, or what you consider to be "working".

halfer
  • 19,824
  • 17
  • 99
  • 186
eerorika
  • 232,697
  • 12
  • 197
  • 326