0

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);

}
Paul92
  • 8,109
  • 1
  • 17
  • 33
Visluck
  • 47
  • 6
  • 2
    You get it because you have *undefined behavior*. You get the undefined behavior because you access the vector out of bounds. You access the vector out of bounds because it's empty (the size is zero). – Some programmer dude Jun 06 '19 at 23:04
  • The size of vector will be never zero because when object is created constructor will automatically push -1 into vector . – Visluck Jun 07 '19 at 00:33
  • ***The size of vector will be never zero because when object is created constructor will automatically push -1 into vector*** That is wrong. `v[0] = -1;` tries to access a non existing position in an empty vector. It will not increase the size of the vector like push_back(); – drescherjm Jun 07 '19 at 00:35
  • @Visluck *The size of vector will be never zero* -- You want proof that this statement is false? `Heap() { std::cout << "The size of the vector is " << v.size() << std::endl; v[0] = -1; }` -- What do you see printed on the screen? – PaulMcKenzie Jun 07 '19 at 01:00

1 Answers1

5
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.

Khoyo
  • 1,073
  • 7
  • 17