分段错误(核心转储)链接列表

时间:2015-10-16 04:14:44

标签: c

我非常关注我的智慧。让这段代码工作(大部分)都很好。我通过执行“gcc -o selfRef selfRef.o”而不是“gcc -c selfRef.c”来编译它。不确定编译C文件的正确方法,但我开始得到分段错误错误,我似乎无法弄清楚如何解决它。

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

由于

    #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);       

}

1 个答案:

答案 0 :(得分:4)

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

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

您使用%s代替%d。 %s用于字符串。因此,printf的认为你有一个字符串和运行野生寻找一个空终止(strings in C are null terminated),但只给了一个int,所以它走了你的内存边界的,你会得到一个segfault。

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

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

这看似微不足道,但是printf内存问题是经典的C.最臭名昭着的C漏洞是利用打印功能的缓冲区溢出。

相关问题