c - 获取数组输入时出现段错误

标签 c

这是一段代码,当我使用 gcc 编译器运行它时,我得到段错误。这实际上是什么以及为什么会在这段代码中发生。

#include<stdio.h>
#include<math.h>
#include<stdlib.h>
struct node
{
    int number;
    struct node *right;
    struct node *left;
};
void funct(struct node *root,int num,int counter,int limit,int *arr)
{
    if(root==NULL)
    {
    root=malloc(sizeof(struct node));
    }

    if(counter>=limit)
    {
        root->left=NULL;
        root->right=NULL;
        return;
    }
    root->number=num;
    counter++;
    funct(root->left,num+arr[0],counter,limit,arr);
    funct(root->right,num+arr[1],counter,limit,arr);

}
void getdata(struct node *root,int *res,int counter)
{
    while(root->left!=NULL&&root->right!=NULL)
    {
        getdata(root->left,res,counter);
        getdata(root->right,res,counter);
    }
    res[counter]=root->number;
}
int main()
{
    int t,i,n,arr[2],*res,size,j;
    scanf("%d",&t);
    j=0;
    while(j++<t)
    {
    scanf("%d",&n);
    scanf("%d %d",&arr[0],&arr[1]);
    size=pow(2,n-1);
    res=malloc(size*sizeof(int));
    if(res==NULL)
    {
        printf("you got this one");
    }
    struct node *root=NULL;
    funct(root,0,0,n,arr);
    getdata(root,res,0);
    for(i=0;i<size;i++)
    {  
        printf("%d\t",res[i]);
    }
    }
    return 0;
}

这里,我在ubuntu上使用gcc编译器。我尝试跟踪问题并认为scanf中的arr输入有问题。

最佳答案

您正在使用malloc的返回而不检查失败。如果 size = pow(2, n-1) 太大,malloc 将失败并返回空指针。取消引用空指针通常会导致段错误。错误检查示例:

res=malloc(size*sizeof(int));
if(res){
struct node *root=NULL;
funct(root,0,0,n,arr);
getdata(root,res,0);
}
else {//handle error}

关于c - 获取数组输入时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26696814/

相关文章:

c - 如何按名称(字符串)排序和搜索 BST?

c - C 数组的水平和垂直直方图

c - 使用指针进行类型转换

c - 使用嵌套的 printf 语句给出奇怪的输出

C 内存泄漏问题

c - 在C中读取文本文件,将行分成多个变量

c - 如何使用 epoll 管理从多个客户端接收多个缓冲区?

c - 按下 Winapi 按钮

c - 当进程在 waitpid 中等待时如何处理信号?

CONTROL\crashes 调用 getline