Search code examples
c++linked-listcoredumpunordered-set

Core dumped while performing linked list operation in "CodePad" (which is an online C++ compiler)


Recently I have been practising some linked list coding questions. I just started using unordered_set. The question is, "Write code to remove duplicates from an unsorted linked list". I have used unordered_set for this. But I'm having the problem of "coredump" when I try to initialize the linked list.

It displays the array when I comment out the last 3 lines of populateList. It displays core dumped when ever I try to access head in populateList.

This is the entire code I have written. I have written this in codepad website.

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

If I comment out the content in the for loop below everything runs smoothly.

    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;
}

Solution

  • The problem is that in your for loop you set next to NULL then try to dereference it on next iteratation

    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;
    }
    

    if you unroll this

    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];
    ...