C 语言,分段错误(已创建核心转储)
C language, segmentation fault(core dump created)
在我的二叉树中创建 child 后,它给我核心转储错误,if 条件完美运行,但是当我尝试将 sx child 作为参数传递时,它给出错误而且我不知道如何解决它。
#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;
}
首先是内存分配的问题
node root=(node)malloc(sizeof(node));
代表
struct nodes * node = (struct nodes *) malloc(sizeof(struct nodes *));
虽然,应该是
struct nodes * node = malloc(sizeof(struct nodes));
因此,从本质上讲,您分配的内存 比预期的(整个变量)少方式。
然后,一旦修复,稍后 build(n->sx);
也会调用 undefined behavior,因为您正试图将一个未初始化的指针传递给函数,并取消引用它。
也就是说,please see this discussion on why not to cast the return value of malloc()
and family in C
.。
在我的二叉树中创建 child 后,它给我核心转储错误,if 条件完美运行,但是当我尝试将 sx child 作为参数传递时,它给出错误而且我不知道如何解决它。
#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;
}
首先是内存分配的问题
node root=(node)malloc(sizeof(node));
代表
struct nodes * node = (struct nodes *) malloc(sizeof(struct nodes *));
虽然,应该是
struct nodes * node = malloc(sizeof(struct nodes));
因此,从本质上讲,您分配的内存 比预期的(整个变量)少方式。
然后,一旦修复,稍后 build(n->sx);
也会调用 undefined behavior,因为您正试图将一个未初始化的指针传递给函数,并取消引用它。
也就是说,please see this discussion on why not to cast the return value of malloc()
and family in C
.。