简体   繁体   English

在Mac中用C创建二进制树时出现总线错误10

[英]Bus Error 10 on Mac when creating a binary tree in C

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. 我在尝试使用C语言中的结构创建二进制树时遇到总线错误。请向我提出解决此总线错误的解决方案。 I am compiling on Mac OSX. 我正在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 输出:总线错误10

In your newNode function you are defining the structure pointer struct node* inode but not allocating it. newNode函数中,您正在定义结构指针struct node* inode但未分配它。 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. inode将具有随机值(作为地址),访问该地址时,可能会出现总线错误。

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); 
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM