【问题标题】:Core dumped while performing linked list operation in "CodePad" (which is an online C++ compiler)在“CodePad”(在线 C++ 编译器)中执行链表操作时核心转储
【发布时间】:2017-08-24 12:59:16
【问题描述】:

最近我一直在练习一些链表编码问题。我刚开始使用 unordered_set。问题是,“编写代码以从未排序的链表中删除重复项”。我为此使用了 unordered_set。但是当我尝试初始化链表时,我遇到了“coredump”的问题。

当我注释掉populateList 的最后3 行时,它会显示数组。当我尝试访问 populateList 中的 head 时,它会显示核心转储。

这是我写的全部代码。我已经在键盘网站上写了这个。

#include <iostream>
#include<vector>
#include<string.h>
#include<math.h>
#include<sstream>
#include<string>
#include<stdio.h>
#include<algorithm>

#include<unordered_set>
using namespace std;

struct Node
{
    int data;
    Node *next;
};
Node *head=NULL;
void populateList(Node *head)
{
    int arr[]={7,1,2,3,4,5,4,3,5,7,3,9,3,7,3,6,2,5,7,4};
    cout<<"\n\n";
    int n=sizeof(arr)/sizeof(int);
    for(int i=0;i<n;i++)
    {
        cout<<arr[i]<<" ";
    }
    Node *ptr=head;

如果我在下面的 for 循环中注释掉内容,一切都会顺利进行。

    for(int i=0;i<n;i++)
    {
        ptr->data=arr[i];
        ptr->next=NULL;
        ptr=ptr->next;
    }
}
int main()
{
    Node *ptr=head, *prev=head;
    populateList(head);
    unordered_set<int> A;
    while(ptr!=NULL)
    {
        cout<<ptr->data<<" ";
    }
    while(ptr!=NULL)
    {
        if(A.find(ptr->data)==A.end())
        {
            A.insert(ptr->data);
        }
        else
        {
            prev->next=ptr->next;    
            delete ptr;
            ptr=prev->next;
        }
        prev=ptr;
        ptr=ptr->next;
    }
    ptr=head;
    cout<<"\n\n";
    while(ptr!=NULL)
    {
        cout<<ptr->data<<" ";
    }
    return 0;
}

【问题讨论】:

  • 该代码中疑似缺少new
  • 你调用populateList(head) where head == NULL,然后继续用head-&gt;data = ...;取消引用这个NULL指针
  • 把之前的cmets的内容换成一句话:你不是用new操作符分配list的节点。
  • 但是我遇到了“coredump”的问题——换句话说,你的程序有错误。我认为是时候使用调试器并了解程序员如何解决这些问题(而不是仅仅编写代码,看到它不起作用,并让 SO 贡献者调试您编写的代码)。

标签: c++ linked-list coredump unordered-set


【解决方案1】:

问题是在你的 for 循环中你设置为 NULL 然后尝试在下一次迭代中取消引用它

for(int i=0;i<n;i++)
{
    ptr->data=arr[i];
    ptr->next=NULL; // now ptr->next is NULL
    ptr=ptr->next; // ptr = ptr->next = NULL;
}

如果你展开这个

int i = 0;
ptr->data=arr[0];
ptr->next=NULL;
ptr=ptr->next; // ptr = ptr->next = NULL;
i++;
// because we set ptr to NULL this is dereferencing the NULL pointer
ptr->data=array[1];
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-19
    • 1970-01-01
    • 1970-01-01
    • 2015-06-23
    • 1970-01-01
    • 1970-01-01
    • 2015-08-11
    相关资源
    最近更新 更多