gpt4 book ai didi

c - 在非常小的代码片段中寻找 SEGFAULT 原因

转载 作者:行者123 更新时间:2023-11-30 15:52:35 26 4
gpt4 key购买 nike

简单地说,我正在为基本数据库编写单链表的原始实现。当用户请求打印索引下列出的元素高于数据库中当前记录数量时,我不断出现段错误,但仅当差值为 1 时。对于更高的数字,它只会触发我在那里编写的错误系统。

代码是:

void print_spec(List* head)
{
int index, i, is_correct=1;
List * current=NULL; //List is typedef'ed structure consisting variables for data and pointer assumed to be bound to next element in list
printf("\nInput the element index: ");
scanf("%d", &index);
if(head!=NULL)
{
current=head;
for (i=0; i<index; i++)
{
if(current==NULL)
{
printf("There is no such element");
is_correct=0;
break;
}
else current=current->next;
}
if(is_correct!=0) print(current); //this function simply prints out variables from element
}
else printf("List is empty, can't print");
}

我猜有一个小错误,但正如我在主题中提到的,我现在正在搜索它大约 4 个小时,花了 2 个小时在试错方法上考虑循环计数器中可能的范围超出,但收到了没有正确的结果。

最佳答案

循环可能会退出,因为 i==index while current==NULL。在这种情况下,永远不会设置 is_ Correct ,并且当您的程序尝试打印 NULL 列表元素时,它可能会失败。您可以通过将代码更改为类似的内容来避免这种情况并简化循环

for (i=0; i<index && current!=NULL; i++) 
{
current=current->next;
}
if (current != NULL)
print(current);

关于c - 在非常小的代码片段中寻找 SEGFAULT 原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14297164/

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