【问题标题】:Bus Error 10 on Mac when creating a binary tree in C在 C 中创建二叉树时,Mac 上出现总线错误 10
【发布时间】:2013-04-18 04:54:43
【问题描述】:

我在尝试使用 C 中的结构创建二叉树时遇到总线错误。 请建议我解决此总线错误的解决方案。我正在 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();    

}

输出:总线错误 10

【问题讨论】:

    标签: c macos pointers data-structures binary-tree


    【解决方案1】:

    在您的newNode 函数中,您定义了结构指针struct node* inode,但没有分配它。然后访问它来存储数据,这是不正确的。

    inode 将具有随机值(作为地址),当访问该地址时,您可能会遇到总线错误。

    你需要在你的函数中分配内存,比如

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

    【讨论】:

      猜你喜欢
      • 2019-09-23
      • 1970-01-01
      • 1970-01-01
      • 2022-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-08
      • 2012-01-09
      相关资源
      最近更新 更多