segmentation fault

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;
    }
}

It crashes on line 63 and 46. You check for current->next while you should check for current only.
That doesn't cause a problem on my end. If I remove the print function then it compiles just fine.
Last edited on
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.
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.