Getting a segmentation fault trying to pass a node

Viewed 199

I'm new to C and I just started learning how to use pointers. I'm trying to create a function (r) that adds to a bst depending on if the parameter (int n) is greater than the root nodes value. However, I keep getting segmentation fault (core dumped) after running the following code. How do I fix it so that it can run normally without error.

struct node  {
    int data;
    struct node *left;
    struct node *right;
    }node;

struct node* newNode(int data){
    struct node* node = (struct node*)malloc(sizeof(struct node));
    node->data = data;
    node->left = NULL;
    node->right = NULL;
    return (node);
    }

void r (int n, struct node* root);

int main() {

    struct node *root = newNode(1);
    printf("%d", root->data);
    r(10, root);
    return 0;
    }

void r(int n, struct node* root){
    if(n > root->left->data){
       root->right = newNode(n);
       printf("New right is: %d\n", root->right->data);
    }
    else if(n < root->left->data){
       int a = root->left->data;
       root->left->data = n;
       root->right->data = a;
       printf("New left is: %d\n", root->left->data);

    }

       return;
    }
1 Answers

In the r function you wrote:

root->left->data

But root->left is equal to NULL. This will cause a segfault because you can't dereference a null pointer.

You can check for validity by doing something like:

// Make sure the left node exists, then do the test after
if (root->left && root->left->data > n)

since doing root->left will cause it to check that it's non-zero (meaning not NULL).

Related