【问题标题】:Segmentation fault creating a binary search tree in C在 C 中创建二叉搜索树的分段错误
【发布时间】:2017-07-26 00:20:05
【问题描述】:

我刚开始学习 C 语言中的树,但我的代码不断出现分段错误。该代码旨在创建树,然后返回树中的最小值和最大值。我查看了其他人的代码,但似乎找不到我所犯的错误。如果有人能发现它,那将非常有帮助。

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

typedef struct node{
    int data;
    struct node* right;
    struct node* left;
}node;

node* Insert(node* root, int data);
int Min(node* root);
int Max(node* root);
node* GetNewNode(int data);

int main(void){
    int min, max, data, x;
    node* root = NULL;
    printf("how many elements would you like to be in the tree\n");
    scanf("%i", &x);
    for(int i = 0; i < x; i++){
        scanf("%i", &data);
        root = Insert(root, data);
    }
    min = Min(root);
    max = Max(root);
    printf("the min value is %i, and the max value is %i\n", min, max);

}

node* Insert(node* root, int data){
    if(root == NULL){
        root = GetNewNode(data);
    }
    else if(data <= root->data){
        root->left = Insert(root->left, data);
    }
    else{
        root->right= Insert(root->right, data);
    }
    return root;
}

node* GetNewNode(int data){
    node* newNode = (node*)malloc(sizeof(node*));
    newNode->data = data;
    newNode->left = newNode->right = NULL;
    return newNode;
}

int Min(node* root){
    node* temp = root;
    if(root->left == NULL){
        return root->data;
    }
    else{
        return Min(root->left);
    }
}

int Max(node* root){
    node* temp = root;
    if(root->right == NULL){
        return root->data;
    }
    else{
        return Max(root->right);
    }
}

【问题讨论】:

  • node* newNode = (node*)malloc(sizeof(node*)); --> node* newNode = (node*)malloc(sizeof(node));node* newNode = malloc(sizeof(*newNode));
  • 这是一个很好的捕捉@BLUEPIXY。 Mohammed 如果您在 GDB 下执行并检查回溯,那就太好了,这也是学习调试的好机会。

标签: c tree binary-search-tree


【解决方案1】:

改变这一行:

node* newNode = (node*)malloc(sizeof(node*));

到这里:

node* newNode = (node*)malloc(sizeof(node));

【讨论】:

    【解决方案2】:

    这一行:

    node* newNode = (node*)malloc(sizeof(node*));
    

    您正在分配sizeof(node *)bytes,这实际上是您系统的指针大小。你想要的是分配足够的内存来保存 结构本身 而不是指向它的指针。这样的事情会起作用:

    node* newNode = (node*)malloc(sizeof(node) * sizeof(char));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多