c - 为什么会出现Segmentation Core dumped?我做了很多次链接列表,但不明白为什么这段代码中有一个转储

标签 c list

我不明白为什么会出现“Segmentation fault (core dumped)”...它发生在我在 push 函数中调用 push 函数时。

node* push(node* head, node*cur, int n)
{
    if(head==NULL)
    {
        head=(node*)malloc(sizeof(node));
        ins(n, head);
        head->next=NULL;        
    }
    else
    {
        cur->next=(node*)malloc(sizeof(node));      //because initially head and cur are same!      
        cur=cur->next;
        ins(n, cur);
        cur->next=NULL; 
    }
    printf("\nPress 1 to continue insertion: ");
    int ch; 
    scanf("%d", &ch);
    if(ch==1)
    {
        printf("\nEnter Digit to push: ");
        int dig;
        scanf("%d", &dig);
        push(head, cur, dig);
    }
    return head;
}


void disp(node* head)
{
    node* cur=head;

    printf("printing::: %d and %d and %p and %p\n", head->dat, cur->next->dat, head, cur);

    while(cur!=NULL)
    {
        printf("=>");
        cur=cur->next;
    }
}

最佳答案

问题好像是行

cur->next=(node*)malloc(sizeof(node)); 因为正如您所说的 cur 与 head 相同,所以 cur 为 NULL 并且访问 next 为 NULL 是无效的。

要解决这个问题

if(head==NULL)
    {
        head=(node*)malloc(sizeof(node));
        ins(n, head);
        head->next=NULL;  
        cur=head;   // <--change here
    }

这样下一次 cur 将指向 head 并且您可以访问 cur 的 next。

关于c - 为什么会出现Segmentation Core dumped?我做了很多次链接列表,但不明白为什么这段代码中有一个转储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27971040/

相关文章:

c - 创建单链表时出现异常

java - 我的 isEmpty 方法不起作用,我不知道为什么

Python 列表到带键的字典

c - ld.so 无法加载所需的库

c++ - 我应该使用std::list还是有更好的方法?

列表操作

Python 相当于 R 的 Pandas 数据框列表

c - 如何用AST树或其他工具做静态代码逻辑分析?

c - 在地址中使用先前参数时 Sscanf 未初始化的值

c - 在 Eclipse 中调试 C 程序 : Failed to execute MI command: -data-disassemble