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

时间:2013-01-12 19:35:48

标签: c

简单地说,我正在为基本数据库编写非常原始的单链表实现。当用户请求打印索引下列出的元素高于DB中的当前记录数量时,我一直收到段错误,但只有当差异为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个小时的试错法,但收到了没有正确的结果。

2 个答案:

答案 0 :(得分:1)

由于i==index current==NULL,您的循环可能会退出。在这种情况下永远不会设置is_correct,并且当您尝试打印NULL列表元素时,您的程序可能会失败。您可以通过将代码更改为

来避免这种情况并简化循环
for (i=0; i<index && current!=NULL; i++) 
{
    current=current->next;
}
if (current != NULL)
    print(current);

答案 1 :(得分:0)

已更新

在上面的原始代码中,替换:

if(is_correct!=0) print(current);

if(is_correct!=0 && current != NULL)
    print(current);
else
    printf("Trying to print null List entry\n");

假设列表中有10个条目,索引恰好是11 那么这是在i = 10时发生的事情:

for (i=0; i<index; i++) // i(10) < index(11)
{
    if(current==NULL) // not true as you have a 10th element
    {
        printf("There is no such element");
        is_correct=0;
        break;
    }
    else current=current->next; // current is now NULL as there is no 11th element
}
if(is_correct!=0) print(current); // crash, trying to print NULL
相关问题