Search code examples
c++c++11heappriority-queue

Segmentation fault in a custom Heap


It is not even performing push operation. It not calling push function just constructor call and segmentation fault. Why is this happening?

class Heap {
    vector<int> v;

     void Heapify(int x) {
        int mi = x;
        int l = 2 * x;
        int r = 2 * x + 1;

        if (v[mi] > v[l] && l < v.size()) {
            mi = l;


        }
        if (v[mi] > v[r] && r < v.size()) {
            mi = r;
        }

        if (mi != x) {
            swap(v[mi], v[x]);
            Heapify(mi);
        }
                       }
public:
    Heap() {

        v[0] = -1;
    }
    void push(int x) {

        v.push_back(x);
        int i = v.size()-1;
        int p = i / 2;
        while (i > 1 && v[i] < v[p]) {


            swap(v[p], v[i]);
            i = p;
            p = p / 2;

        }

    }
    void pop() {
        swap(v[v.size() - 1], v[1]);
        v.pop_back();
         Heapify(1);
    }


};
int main(){

    Heap h;
    h.push(5);

}

Solution

  • Heap() {
            v[0] = -1; // Segfault.
    }
    

    At that point, the vector v is empty, and you try to assign the first element (v[0]). This is outside the bounds of the vector, so the behaviour of the program is undefined (here, a crash).

    You should use v.push_back(-1) if you really want to insert -1 at the start of the vector.