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

时间:2014-11-02 06:55:43

标签: 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有些问题。

1 个答案:

答案 0 :(得分:4)

您正在使用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}