【问题标题】:Segmentation Fault(Core Dump) Linked List分段故障(核心转储)链表
【发布时间】:2015-10-16 04:14:44
【问题描述】:

到此为止,我已经不知所措了。让这段代码(大部分)正常工作后。我通过执行“gcc -o selfRef selfRef.o”而不是“gcc -c selfRef.c”来编译它不确定编译C文件的正确方法是什么,但我开始收到分段错误错误,我似乎无法弄清楚如何解决它。

我在我的插入方法中插入了打印语句,所以我知道代码在中断之前甚至没有调用它。知道如何解决这个问题吗?

谢谢

    #include <stdio.h>
    #include <stdlib.h>
    #include <stdbool.h>    
    struct Node
    {
    int value;
    struct Node *next;
    };    
    struct Node *head;    
    int main( int argc, char* argv[] )
    {
     #define True 1
     #define False 0
     typedef int Boolean;    
     struct Node *head = NULL;   
     int i;    
     printf("Your linked list:\n");    
    //inserts items into the list
     for (i = 1; i < 20; i += 2)
     {
        insert(i,&head);
     }     
     printList(head);
    }
    insert(int x, struct Node **pL)
    {
        printf("Inserts");      
        if(*pL == NULL)
        {
        struct Node *temp = (struct Node*)malloc(sizeof(struct Node));
        (*pL) = temp;
        (*pL) -> value = x;
        (*pL) -> next = NULL;
        }
        else
        {
         insert(x,&((*pL) -> next));
         printf("Inserts");
        }
     }    
    delete(int x, struct Node **pL)
    {
        if(*pL == NULL)
        {
         if(((*pL) -> value) == x)
         {
            (*pL) = (*pL) -> next -> next;
         }
        else
        {
            lookup(x, head -> next);
        }
    }
  }
lookup(int x, struct Node *head)
{
    if(head -> next == NULL)
    {
        return;
    }
    else if(head -> value == x)
    {
        return True;
    }
    lookup(x,(head) -> next);
}   
printList(struct Node *head)
{       
     if(head == NULL)
     {
        printf("The list is empty");
        return;
     }
     printf("Node: %s",head -> value);
     printList(head -> next);       

}

【问题讨论】:

  • 您是否尝试过使用 valgrind 或其他工具来确定段错误发生的位置?这肯定会帮助您找到原因并可能解决问题。
  • if(*pL == NULL) { if(((*pL) -&gt; value) == x) 是错误的。和 lookup(x, head -&gt; next); ,不使用全局变量 head
  • @BLUEPIXY 第一个东西是临时测试的东西 // 代码是实际进入该方法的内容。
  • 您应该使用gcc -Wall -Wextra -g 进行编译,然后使用调试器 (gdb)。请注意,修复我损坏的代码问题在这里是题外话。

标签: c


【解决方案1】:

您的运行时错误在 printList 函数的第 127 行附近。罪魁祸首是printf:

printf("Node: %s",head -&gt; value);

您使用 %s 而不是 %d。 %s 用于字符串。所以,printf 认为你有一个字符串,并且正在疯狂搜索空终止符 (strings in C are null terminated),但你只给了它一个 int,所以它超出了你的内存范围,你得到了一个段错误。

此更改导致程序正常完成:

printf("Node: %d",head -&gt; value);

这可能看起来微不足道,但 printf 内存问题是典型的 C。最臭名昭著的 C 漏洞利用是利用打印函数的缓冲区溢出。

【讨论】:

    猜你喜欢
    • 2016-09-09
    • 2014-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多