segmentation fault
Jun 16, 2015 at 3:17pm UTC
So I'm practicing templates with data structures and my print function gives me a segmentation fault when I want to print my whole list.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
#include <iostream>
using namespace std;
template <class T>
class List{
private :
struct Node{
T data;
Node * next;
};
Node * head;
Node * current;
public :
List();
//~List();
void push_back(T val);
void print();
};
template <class T>
List<T>::List()
{
head = nullptr ;
}
template <class T>
void List<T>::push_back(T val)
{
Node * n = new Node;
n->data = val;
n->next = nullptr ;
if (head == nullptr )
{
head = n;
}
else {
current = head;
while (current->next != nullptr )
{
current = current->next;
}
current->next = n;
}
}
template <class T>
void List<T>::print()
{
if (head = nullptr )
{
cout << "List is empty" << endl;
}
else {
current = head;
while (current->next != nullptr )
{
cout << current->data << " " ;
current = current->next;
}
cout << current->data;
}
}
int main()
{
List<string> one;
one.push_back("red" );
one.print();
}
What confuses me more is why does this work?
1 2 3 4 5 6
template <class T>
void List<T>::print()
{
current = head;
cout << current->data;
}
but this doesn't?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
template <class T>
void List<T>::print()
{
if (head = nullptr )
{
cout << "List is empty" << endl;
}
else {
current = head;
while (current->next != nullptr )
{
cout << current->data << " " ;
current = current->next;
}
cout << current->data;
}
}
Jun 16, 2015 at 3:26pm UTC
It crashes on line 63 and 46. You check for current->next
while you should check for current
only.
Jun 16, 2015 at 5:41pm UTC
That doesn't cause a problem on my end. If I remove the print function then it compiles just fine.
Last edited on Jun 16, 2015 at 5:43pm UTC
Jun 16, 2015 at 5:53pm UTC
if (head = nullptr )
Guess what this line is doing. And which branch would be chosen, side effects it will have and what it will lead to.
Jun 16, 2015 at 6:29pm UTC
Thanks @MiiNiPaa. I completely overlooked that. Even as I read your post I was wondering why you posted something so obvious but I didn't see the reassigning there.
Topic archived. No new replies allowed.