I have created a simple linked list that allows me to do 3 things; create a linked list, calculate the size of the linked list & print the contents of the linked list.

Although my program crashes when I use the functions:
- int len(node *L); // return length of linked list
- void contents(node *L); // display contents of linked list

Can you help me determine why my program crashes & how to fix it?

I have a feeling it may have to do with the fact I have not set the last element of the linked lists' next pointer to NULL. If so how do I do that?

#include <iostream>

using namespace std;

struct node
  int data;
  node * next;

node * comp(node * L, int x);
int len(node * L);
void contents(node *L);

int main() {
    node * list;
    int n;
    int j;
    cout << "enter the size of the list u wish to create: " << flush;
    cin >> n;
    cout << n << endl;
    for (int i; i<n; i++) {
        cout << "enter ur data x to put in list: ";
        cin >> j;
        list = comp(list,j);
    int m = len(list); // if I do this it crashes
    contents(list);  // if I do this it crashes
    return 0;

node * comp(node * L, int x)
     // returns a pointer to the linked list obtained by inserting
     // a new node containing x at the beginning of the linked list L
    node * newPointer = new node;
    newPointer->data = x;
    newPointer->next = L;
    L = newPointer;
    return L;

int len(node * L)
    // returns the length of linked list L, that is, the number of
    // nodes in L
    node * currentPointer;
    currentPointer = L;
    int counter = 0;
    while (currentPointer != NULL) { 
           currentPointer = currentPointer->next;
    return counter;

void contents(node *L) {
     // print contents/each element of the list
     node * currentp;
     currentp = L;
     while (currentp != NULL) {
           cout << currentp->data << endl;
           currentp = currentp->next;
This article has been dead for over six months. Start a new discussion instead.