3

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
  • 3
    The very first time you call r(10, root) you have if (n > root->left->data).. In this case root->left is NULL. Commented Jun 21, 2019 at 23:09

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

5 Comments

Oh wow, thanks I cant believe I didnt notice that. Thanks a lot.
@CrisManrique Is there a way my answer could be improved? Or is it unacceptable in any way?
No, you were right, I had actually overlooked a simple mistake. You were right on the money. Sorry if I sounded sarcastic.
@CrisManrique Is there any way I can make this answer better?
@CrisManrique If this answer helped you, please mark it as the accepted answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.