Reputation: 16935
I've been trying to rewrite some basic data structures using C++ to refresh my memory on some of the basics of OOP, but I've run into a silly problem already.
I'm trying to build a singly linked list, append the strings "Hello" and "World" to the list, and then view all of the contents within the list. This is a very easy task, but I'm getting a segmentation fault when I run the following code:
driver.cc
#include <iostream>
#include <string>
#include "SinglyLinkedList.h"
int main()
{
SLL<std::string> List;
List.Append("Hello");
List.Append("World");
List.visitAll(std::cout);
return 0;
}
Node.h
#ifndef NODE_H
#define NODE_H
template <class T>
class Node {
public:
Node<T>() {}
Node<T>(T init) { data = init; next = nullptr; }
void setData(T newData) { data = newData; }
void setNext(Node<T> *nextNode) { next = nextNode; }
const T getData() { return data; }
Node<T> *getNext() { return next; }
private:
T data;
Node<T> *next;
};
#endif
SinglyLinkedList.h
#ifndef SINGLY_LINKEDLIST_H
#define SINGLY_LINKEDLIST_H
#include "Node.h"
#include <iostream>
template <class T>
class SLL {
public:
SLL<T>() { head = nullptr; size = 0; }
~SLL<T>() {}
void Append(T added);
void Delete(T deleted);
void visitAll(std::ostream &outs);
private:
Node<T> *head;
long size;
};
template <class T>
void SLL<T>::Append(T added)
{
Node<T> *newNode = new Node<T>(added);
Node<T> *temp = head;
if(temp != nullptr) {
while(temp != nullptr) {
temp = temp->getNext();
}
temp->setNext(newNode); // seg fault here
}
else {
head = newNode;
}
}
template <class T>
void SLL<T>::visitAll(std::ostream &outs)
{
Node<T> *temp = head;
while(temp)
{
outs << temp->getData() << std::endl;
temp=temp->getNext();
}
}
#endif
Just debugging by hand, I create a new node with data
= "Hello"
and next
= nullptr
. This gets appended by the else
in the void SLL<T>::Append
method because temp == nullptr
. However, on the second Append
, the while loop runs once, then crashes when calling the setter of the Node
class. I cannot figure out why this is the case.
I'm expecting to see
Hello
World
Am I being too tunnel-visioned? This is pretty silly. Sorry if it's too basic for SO...
Thanks, erip
Upvotes: 1
Views: 149
Reputation: 206607
while(temp != nullptr) {
temp = temp->getNext();
}
temp->setNext(newNode); // seg fault here
That's because you are breaking out of the while
loop when temp == nullptr
.
Use:
while(temp->getNext() != nullptr) {
temp = temp->getNext();
}
temp->setNext(newNode);
Upvotes: 3
Reputation: 1256
Your while loop in Append
ends with temp
being a null pointer, therefore no temp->setNext()
Upvotes: 1