I am writing a generic linked list in C++ using templates, and am experiencing Segmentation Faults when accessing Node values.
To make the test case simpler, I have implemented a fixed size, two node, linked list.
I have two questions:
1a) Why isn’t aList.headNodePtr->prevNodePtr set to NULL?
1b) Why isn’t aList.tailNodePtr->nextNodePtr set to NULL?
I set both of these values to NULL in the LinkedList constructor, but the output in main shows that:
head prevAddress: 0x89485ed18949ed31
tail nextAddress: 0x7fffe8849679
2) Why does the following line in main() cause a Seg Fault?
aList.headNodePtr->nodeValue = 1;
The full code is below:
#include <iostream>
using namespace std;
template <class T>
class Node {
public:
Node<T>* prevNodePtr;
Node<T>* nextNodePtr;
T nodeValue;
};
template <typename T>
class LinkedList {
public:
Node<T>* headNodePtr;
Node<T>* tailNodePtr;
LinkedList() {
Node<T>* headNodePtr = new Node<T>;
Node<T>* tailNodePtr = new Node<T>;
headNodePtr->prevNodePtr = NULL;
headNodePtr->nextNodePtr = tailNodePtr;
tailNodePtr->prevNodePtr = headNodePtr;
tailNodePtr->nextNodePtr = NULL;
}
~LinkedList() {
headNodePtr = NULL;
tailNodePtr = NULL;
delete headNodePtr;
delete tailNodePtr;
}
};
int main()
{
LinkedList<int> aList;
cout << "head Value: " << aList.headNodePtr->nodeValue << endl;
cout << "head prevAddress: " << aList.headNodePtr->prevNodePtr << endl;
cout << "head nextAddress: " << aList.headNodePtr->nextNodePtr << endl;
cout << "tail Value: " << aList.tailNodePtr->nodeValue << endl;
cout << "tail prevAddress: " << aList.tailNodePtr->prevNodePtr << endl;
cout << "tail nextAddress: " << aList.tailNodePtr->nextNodePtr << endl;
aList.headNodePtr->nodeValue = 1;
}
You’re not actually setting the members, you’re setting the locals you declared in the ctor:
Try this instead: