Unhandled exception in c++ program for doubly linked list

0

I wrote a program for doubly linked list in visual studio 2013, and it threw unhandled exception error at the line marked with comment: -

linked_list_double.h: -

#pragma once
#include<iostream>

template <typename T>
struct Node
{
    T data;
    Node *next, *prev;
};

template <typename T>
class doubleLinkedList
{
private:
    Node<T> *top;
public:
    doubleLinkedList()
    {
        top = nullptr;
    }

    void add(T data)
    {
        Node<T> *temp = new Node<T>;

        temp->prev = nullptr;
        temp->next = top;
        top->prev = temp;     //unhandled exception here
        top = temp;
    }

    void display()
    {
        Node<T> *temp;
        temp = top;
        std::cout<<"nullptr<--->\n";
        while(temp)
        {
            std::cout<<temp->data<<"<--->";
            temp = temp->next;
        }
        std::cout<<"nullptr\n";
    }
};

main.cpp: -

#include "linked_list_double.h"

int main()
{
    doubleLinkedList<int> L;

    L.add(3);
    L.add(4);
    L.display();

    return 0;
}

The error is: -

Unhandled exception at 0x011C4B79 in dataStructures2.exe: 0xC0000005: Access violation writing location 0x00000008.

I have never written a doubly linked list before. I am not sure if there any logical error in the program. Any kind of help would be appreciated.

c++
visual-studio
data-structures
linked-list
asked on Stack Overflow Jul 20, 2019 by krossMett • edited Jul 20, 2019 by krossMett

1 Answer

1

top is null on first add. So any attempt to deference top while it's null is going to crash.

So insted of this:

    top->prev = temp;     //unhandled exception here

Do this:

if (top != nullptr)
{
   top->prev = temp;
}
answered on Stack Overflow Jul 20, 2019 by selbie

User contributions licensed under CC BY-SA 3.0