gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:01:49 25 4
gpt4 key购买 nike

这是一段代码,当我使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com