0

It give me core dump error after I have create a child in my binary tree, the if condition work perfectly, but when I try to pass the sx child as parameter it give error and I don't know how to fix it.

#include <stdio.h>
#include <stdlib.h>

typedef struct nodes *node;

struct nodes{
    int dato;
    node sx;
    node dx;
};

node build(node n){
    printf("Insert the value: ");
    scanf("%d",&n->dato );

    char s[5];
    printf("build  a child? ");
    scanf("\n%s",s);

    if(s[0]=='l')
        build(n->sx);


    return n;
}

int main(int argc, char const *argv[]) {
    system("clear");
    node root=(node)malloc(sizeof(node));
    root=build(root);
    printf("\n\nvalue: %d\n", root->dato);
    return 0;
}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Racerider
  • 116
  • 2
  • 11

1 Answers1

3

Firstly, the problem is in the memory allocation.

 node root=(node)malloc(sizeof(node));

which represents

struct nodes * node = (struct nodes *) malloc(sizeof(struct nodes *));

while, it should have been

struct nodes * node = malloc(sizeof(struct nodes));

So, essentially, you're allocating way less memory (just for a pointer) than the expected (a whole variable).

Then, once fixed, at a later point, build(n->sx); will also invoke undefined behavior, as you're trying to pass an unitialized pointer to function, and dereferencing it.

That said, please see this discussion on why not to cast the return value of malloc() and family in C..

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • Casting malloc or not is a matter of style, >1000 upvotes still don't make it true that it would be an error. Please don't be dogmatic. – Ctx Jan 14 '16 at 18:19
  • @Ctx That's why I did not discuss that here, added the link, and said _please_. Rest, upto the reader. :) – Sourav Ghosh Jan 14 '16 at 18:23
  • If you would be as neutral as you claim, why don't you write "Please see this discussion about casting the return value of malloc() and family in C" – Ctx Jan 14 '16 at 18:35