Reputation: 147
I am trying to implement Linked List in C++. Following is my code and I am getting this exception
First-chance exception at 0x012F4C61 in LinkedList.exe: 0xC0000005: Access violation reading location 0xCDFCA94C.
header file
#pragma once
#include "LinkNode.h"
class LinkedList
{
private:
LinkNode *head;
LinkNode *tail;
public:
LinkNode add(int data);
void print();
LinkNode getHead();
LinkedList(void);
~LinkedList(void);
private:
void modify();
};
Cpp file
#include "stdafx.h"
#include "LinkedList.h"
#include <iostream>
using namespace std;
LinkedList::LinkedList(void)
{
this->head = NULL;
this->tail = NULL;
}
LinkedList::~LinkedList(void)
{
}
LinkNode LinkedList :: add(int data)
{
if(this->head == NULL)
{
this->head = new LinkNode(data);
this->tail = head;
return *head;
}
else
{
LinkNode node(data);
tail->next = &node;
tail = tail->next;
}
}
Main function
int _tmain(int argc, _TCHAR* argv[])
{
LinkedList linklist;
linklist.add(1);
linklist.add(2);
linklist.add(3);
linklist.add(4);
linklist.add(5);
linklist.print();
system("pause");
}
Upvotes: 0
Views: 120
Reputation: 34605
LinkNode node(data);
tail->next = &node;
tail = tail->next;
node
resides on stack and life time of it ends as control leaves the LinkedList::add
member function. Dynamically allocate the tail->next
node instead.
Also destructor needs to properly deallocate the resources dynamically acquired. Currently, the program has memory leaks.
Upvotes: 2