I am getting bus error when I'm trying to create a binary tree using structures in C. Please suggest me a solution to overcome this bus error. I am 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 your newNode
function you are defining the structure pointer struct node* inode
but not allocating it. And then accessing it to store data, which is incorrect.
inode
will have random value (which is taken as address) and when accessing that address, you may get bus error.
You need to allocate memory in your function, like
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.