Robot0110
Robot0110

Reputation: 191

Linked List with C++ and generic template giving segmentation fault error.

I have written this code for a generic linked list:

#include <iostream>
#include <stdio.h>


template <class T> 
struct Node{ 
    T data; 
    Node<T> *next; 
};


template <class T> 
class LinkedList{ 


    Node<T>* head; 
    int size; 

    public: 

        LinkedList<T>() {

            size = 0;
            head = NULL;
        }


        void ll_push(T data){ 
            Node<T>* new_node; 
            new_node->data = data; 
            new_node->next = head; 
            head = new_node; 
            size ++; 
        }

        int ll_size(){ 
            return size; 
        }

        void ll_print_int(){
            Node<T> *start = head; 
            while (start != NULL){ 
                cout<< start->data;
                start = start->next;
                cout<< ","; 
            }
        }


};



int main(){ 

    LinkedList<int> ll;

    for(int i = 0; i < 10; i++){ 
        ll.ll_push(i);
    }

    ll.ll_print_int();

    return 0;
}

But whenever I try to execute ll_print, I get a segmentation fault error. I think I might be misusing pointers at some point but I'm unsure. I'm still a novice in C++, so I would really appreciate if someone could explain what did I do wrong.

Upvotes: 0

Views: 81

Answers (1)

Employed Russian
Employed Russian

Reputation: 213754

But whenever I try to execute ll_print, I get a segmentation fault error.

You are using unintialized pointer right here:

Node<T>* new_node;       // unintialized pointer.
new_node->data = data;

Most likely you want:

Node<T>* new_node = new Node<T>;
new_node = ...

Upvotes: 1

Related Questions