osx - Bus Error 10 on Mac when creating a binary tree in C -


i getting bus error when i'm trying create binary tree using structures in c. please suggest me solution overcome bus error. compiling on mac osx.

#include <stdio.h> #include <stdlib.h>  struct node {     int data;     struct node* left;     struct node* right; };  struct node* newnode(int data) {    struct node* inode ;   inode->data = data;    inode->left = null;    inode->right = null;   printf("%d\n", inode->data);   return(inode);  }  struct node* insert(struct node* node ,int data){      if(node == null)         return(newnode(data));      else{         if(data <= node->data)             node->left = insert(node->left, data);         else             node->right = insert(node->right, data);         return(node);     }  }  struct node* build123a() {    struct node* root = newnode(2);     struct node* lchild = newnode(1);    struct node* rchild = newnode(3);   root->left = lchild;    root->right= rchild;    return(root);  }  int main(void) {      build123a();      } 

ouput : bus error 10

in newnode function defining structure pointer struct node* inode not allocating it. , accessing store data, incorrect.

inode have random value (which taken address) , when accessing address, may bus error.

you need allocate memory in function,

  struct node* newnode(int data) {        struct node* inode ;       inode = malloc(sizeof(*inode)); //allocate memory       inode->data = data;        inode->left = null;        inode->right = null;       printf("%d\n", inode->data);       return(inode);    } 

Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -