Search code examples
c++iterator

Why am I receiving a heap buffer overflow runtime error


I am doing Leetcode Problem 281. Zigzag Iterator, and I'm getting a run-time error that doesn't seem to be duplicatable on my local computer.

My code is

class ZigzagIterator {
public:
    ZigzagIterator(vector<int>& v1, vector<int>& v2) : v1{v1}, v2{v2}, it1{v1.begin()}, it2{v2.begin()}, first{false} {

    }

    int next() {
        int val{0};
        if(first || it1 == v1.end()) {
            val = *it2;
            it2++;
            first = false;
        }
        else 
        {
            val = *it1;
            it1++;
            cout << (it1 == v1.end()) << " " << *it1 << endl;

            first = true;
        }

        return val;
    }

    bool hasNext() {
        return (it1 != v1.end() || it2 != v2.end());
    }
private:
    // const vector<int> &v1;
    // const vector<int> &v2;
    vector<int> v1;
    vector<int> v2;
    std::vector<int>::iterator it1;
    std::vector<int>::iterator it2;
    bool first;    
};

int main()
{
  vector<int> v1{1,2};
  vector<int> v2{3,4,5,6};
  ZigzagIterator i(v1, v2);
  while (i.hasNext()) cout << i.next();
}

The run-time error is:

AddressSanitizer: heap-buffer-overflow on address 0x602000000038 at pc 0x0000003843a6 bp 0x7ffeea8b3b50 sp 0x7ffeea8b3b48

I put in a print statement in the else clause of next(). On the second print, (it1 == v1.end()) should be evaluating to true, but it seems to evaluate to false on leetcode and true on my local machine. Do I have a code error somewhere?


Solution

  • Your problem is with all of the code that compares it1 and it2 to v1 and v2 in the class. The v1 and v2 class members are copies of v1 and v2 from main, so you can't use it1 and it2 with them since it1 and it2 are iterators in main's vectors, not you classes.

    You need to make the v1 and v2 members references so that everything is refering to the same vector.