1

I'm implementing an unordered linked list in C++ based on first principles. My (partially complete so far) implementation is:

#include <iostream>

class Node {
    int m_data;
    Node *m_next;

public:
    Node(int data)
    {
        m_data = data;
        m_next = nullptr;
    }

    int getData() { return m_data; }
    void setData(int data) { m_data = data; }
    Node* getNext() { return m_next; }
    void setNext(Node *next) { m_next = next; }
};

class UnorderedList {
public:
    Node *m_head;

public:
    UnorderedList()
    {
        m_head = nullptr;
    }

    bool isEmpty() { return m_head == nullptr; }

    void appendToHead(int data)
    {
        Node temp = Node(data);
        temp.setNext(m_head);
        m_head = &temp;
    }

    void remove(int data);
    bool search(int data);
};

int main()
{
    UnorderedList list1;
    list1.appendToHead(32);
    list1.appendToHead(47);
    list1.appendToHead(90);
    std::cout << list1.m_head->getData() << '\n';
    std::cout << list1.m_head->getNext()->getData() << '\n';
    return 0;
}

I am able to correctly print the head of the list as '90', but the next line (i.e. getNext()->getData()) gets printed as a large random number (281314120). What is the reason for this?

  • Never store the address of an object with *automatic storage duration*. You did that in `UnorderedList::appendToHead` method, thus invoking Undefined Behavior – WhiZTiM Mar 18 '17 at 12:07

1 Answers1

1
void appendToHead(int data)
{
    Node temp = Node(data);
    temp.setNext(m_head);
    m_head = &temp;
}

Never store the address of an object with automatic storage duration. That object (in this case, temp) will cease to exist when appendToHead method completes.

You did that and invoked Undefined Behavior. You probably wanted to do:

void appendToHead(int data)
{
    Node* temp = new Node(data);
    temp->setNext(m_head);
    m_head = temp;
}

You should also consider satisfying The Rule Of Five

Rather than raw pointers, additionally explore the use of std::unique_ptr.

Community
  • 1
  • 1
WhiZTiM
  • 19,970
  • 3
  • 36
  • 56
  • Understood, thanks a lot @WhiZTiM! I upvoted but since my reputation is currently 13, it won't show :) – Abhimanyu Sahai Mar 18 '17 at 12:38
  • @AbhimanyuSahai, You are very much welcome. Don't worry, It will show when your rep eventually gets there. :-). You can however, mark the answer as accepted if it solves your problem. – WhiZTiM Mar 18 '17 at 12:40