-2

My code works okay on my linux. Today when I was trying to compile it and test it on my mac, I got an segv error. And later I changed it to another method (not using erase), the error is gone. I guess that I must have done something wrong in using c++ erase. Any ideas?

Before: (Why this one is not working now?)

vector<point> line::internalPoints() const
{
    vector<point> pts = points();

    pts.erase(pts.begin());
    pts.erase(pts.end());

    return pts;
}

After:

vector<point> line::internalPoints() const
{
    vector<point> pts;
    vector<point> ptsTmp = points();

    for (int i = 1; i < ptsTmp.size()-1; ++i)
    {
        pts.push_back(ptsTmp[i]);
    }

    return pts;
}
Daniel
  • 2,576
  • 7
  • 37
  • 51

1 Answers1

1

end() (and possibly begin() as well, if the vector is empty) don't point to an actual element. That means trying to erase it is undefined behaviour.

Possible duplicate of: erasing vector::end from vector

Community
  • 1
  • 1
  • Hmm, but the vector is not empty. Furthermore, why on my ubuntu, it works without any warning? Are you saying it depends on the compiler or depends on the archetcture? – Daniel Mar 01 '14 at 02:34
  • Read the link: "Undefined behavior is allowed to have any behavior, including "just work" on your platform. That doesn't mean that you should be doing it; it's still undefined behavior, and I'll come bite you in the worst ways when you're least expecting it later on." –  Mar 01 '14 at 02:37
  • Okay, +1 for your link. I see now what a "undefined behavior" means. Thanks – Daniel Mar 01 '14 at 02:37