Segmentation fault(core dumped) in CPP

I am confused a bit. I narrowed down it to:

Why having this line:

Node *root, *rootSafe = NULL;

give error:

Segmentation fault(core dumped)

While just switching it like below:

Node *rootSafe, *root = NULL;

runs perfect.

Here is the code, you can test.

#include <iostream>
using namespace std;
struct Node{
    int data;
    Node *left, *right;
    Node(int d){
        this->data = d;
        this->left = this->right = NULL;
    }
};
Node *newNode(int d){
    Node *temp = (Node *)malloc(sizeof(Node));
    temp->data = d;
    temp->left = temp->right = NULL;
    return temp;
}
void printInorder(Node *root){
    if(root == NULL){
        return;
    }
    else{
        printInorder(root->left);
        cout << "--" << root->data;
        printInorder(root->right);
    }
}
int main()
{
    //cout << "Hello World";
    Node *rootSafe, *root = NULL;
    int arr[] = {5, 3, 1, 4, 6};
    int sizeArr = sizeof(arr)/sizeof(arr[0]);
    
    for(auto i = 0; i < sizeArr; i++){
        if(root == NULL){
            rootSafe = newNode(arr[i]);
            root = rootSafe;
        }
        else{
            while(root != NULL){
                if(arr[i] < root->data){//Move left
                    if(root->left == NULL){
                        root->left = newNode(arr[i]);
                        root = NULL;
                    }
                    else{
                        root = root->left;
                    }
                }
                else{//Move right
                    if(root->right == NULL){
                        root->right = newNode(arr[i]);
                        root = NULL;
                    }
                    else{
                        root = root->right;
                    }
                }
            }
        }
        root = rootSafe;
    }
    
    cout << "n Print Inorder: ----"; printInorder(rootSafe);
    return 0;
}

Answer

Without fiddling with your code, I think this:

Node *root, *rootSafe = NULL;

Doesn’t do what you think it does. Do you think it sets both to NULL? It doesn’t. root gets some random value and rootSafe gets NULL.

This might be what you really want:

Node *root = NULL, *rootSafe = NULL;

Frankly, I personally hate (and it’s against coding conventions at some work places) specifying multiple variables on the same line. You will not find this in my code. Instead, you will see:

Node * root = nullptr;
Node * rootSafe = nullptr;

Note also that in modern C++, NULL is not a pointer. Get in the habit of using nullptr.