1

Consider the following snippet

class ItrTest {
private:
    std::map<int, long> testMap;
    std::map<int, long>::iterator itr;

public:
    ItrTest(std::map<int, long> testMap): testMap(testMap) {
        itr = testMap.begin();
    }

    void printNext() {
        // itr = testMap.begin();
        for (; itr != testMap.end(); itr++) {
            cout<<"Key: "<<itr->first<<" Value:"<<itr->second<<endl;
        }
    }
};

int main() {
    std::map<int, long> m{
        { 0, 100l },
        { 1, 200l },
        { 2, 300l },
        { 3, 400l },
        { 4, 500l },
    };

    ItrTest t(std::move(m));
    t.printNext();
}

This throws a segmentation fault when trying to access the values inside the iterator. It is obvious this happens because the iterator becomes invalid (for me after a couple of iterations. Maybe it behaves differently on different systems). If I uncomment the first line of the function printNext() it works fine. I would like to get an explanation for this behaviour.

1
  • testMap(testMap)?! Why would anyone do that?! Commented Sep 6, 2019 at 16:34

1 Answer 1

3

In the constructor, for itr = testMap.begin();, testMap refer to the function parameter, not the data member. It'll be destryoed when get out of the constructor, left itr dangled. Any dereference on it later leads to UB.

You could change it to

itr = this->testMap.begin();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.