【问题标题】:C language, segmentation fault(core dump created)C 语言,分段错误(创建核心转储)
【发布时间】:2016-01-14 18:02:21
【问题描述】:

在我的二叉树中创建子节点后,它给了我核心转储错误,if 条件完美地工作,但是当我尝试将 sx 子节点作为参数传递时,它给出了错误,我不知道如何修复它.

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

typedef struct nodes *node;

struct nodes{
    int dato;
    node sx;
    node dx;
};

node build(node n){
    printf("Insert the value: ");
    scanf("%d",&n->dato );

    char s[5];
    printf("build  a child? ");
    scanf("\n%s",s);

    if(s[0]=='l')
        build(n->sx);


    return n;
}

int main(int argc, char const *argv[]) {
    system("clear");
    node root=(node)malloc(sizeof(node));
    root=build(root);
    printf("\n\nvalue: %d\n", root->dato);
    return 0;
}

【问题讨论】:

标签: c pointers segmentation-fault typedef dynamic-memory-allocation


【解决方案1】:

首先,问题出在内存分配上。

 node root=(node)malloc(sizeof(node));

代表

struct nodes * node = (struct nodes *) malloc(sizeof(struct nodes *));

应该是这样的

struct nodes * node = malloc(sizeof(struct nodes));

因此,从本质上讲,您分配的内存方式(仅用于指针)比预期的(整个变量)要少。

然后,一旦修复,稍后,build(n-&gt;sx); 也将调用 undefined behavior,因为您尝试将一个未初始化的指针传递给函数,并取消引用它。

也就是说,please see this discussion on why not to cast the return value of malloc() and family in C.

【讨论】:

  • 铸造 malloc 与否是一个风格问题,>1000 次投票仍然不能证明这将是一个错误。请不要教条。
  • @Ctx 这就是为什么我没有在这里讨论,添加链接,并说。休息,由读者决定。 :)
  • 如果您像您声称的那样中立,为什么不写“请参阅有关在 C 中强制转换 malloc() 和 family 的返回值的讨论”
猜你喜欢
  • 1970-01-01
  • 2022-01-14
  • 2017-02-25
  • 2016-07-12
  • 2018-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多