Home>

Segmentation fault: 11 error when trying to create a binary heap in C ++. I did a lot of searching on the web about the binary heap, but it didn't help. I want to find each level. I would like someone to tell me how to solve it.

Error message
Segmentation fault: 11
Applicable source code

C ++

include<iostream>
using namespace std;
struct node {
  struct node * parent;// parent
  struct node * left;// left child
  struct node * right;// right child
  int floor;// hierarchy
};
int main () {
    node * n;
    n->floor = 0;
    int i = 0;
    while (i<10) {
        node * left, * right;
        n->left = left;
        n->left->floor = n->floor + 1;
        n->right = right;
        n->right->floor = n->floor + 1;
        n = n->left;
        i ++;
    }
    cout<<n->floor<<endl;
    cout<<n->left->floor<<endl;
    cout<<n->left->->left->floor<<endl;
}
c c++
  • Answer # 1

    Declaring a pointer variable does not secure node.
    Let's secure node with new node.

    # include
    using namespace std;
    struct node {
        struct node * parent;// parent
        struct node * left;// left child
        struct node * right;// right child
        int floor;// hierarchy
    };
    int main ()
    {
        node * n = new node;
        n->floor = 0;
        node * root = n;
        int i = 0;
        while (i<10) {
            node * left = new node, * right = new node;
            n->left = left;
            n->left->floor = n->floor + 1;
            n->right = right;
            n->right->floor = n->floor + 1;
            n = n->left;
            i ++;
        }
        for (n = root;n;n = n->left)
            cout<floor<


    Actually, it is better to initialize all of parent, left, and right when new is executed.