-1

I've simple C++ program to traverse a linked list. It runs perfectly in ideone . When I run this in my mac terminal it throws segmentation fault. When I uncomment //printf("Node"); line from traverse function it runs perfectly. I'm not able to understand this behavior.

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
typedef struct node {
    int data;
    struct node *next;
} Node;

void traverseLinkedList(Node *start) {
    while(start) {
        //printf("Node");
        cout << start->data << "->";
        start = start->next;
    }
    cout << "NULL" << endl;
}
int main() {
    Node *start = (Node*) malloc(sizeof(Node));
    Node *a = (Node*) malloc(sizeof(Node));
    Node *b = (Node*) malloc(sizeof(Node));
    start->data = 0;
    a->data = 1;
    b->data = 2;
    start->next = a;
    a->next = b;
    traverseLinkedList(start);
    traverseLinkedList(a);
    traverseLinkedList(b);
    return 0;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Rohit Pal
  • 1
  • 4

1 Answers1

3

You forgot this statement

b->next = nullptr;

Otherwise the program has undefined behavior due to the condition in this while statement in the function traverseLinkedList

while(start)

Take into account that in C++ you should use the operator new instead of the C function malloc.

For example

Node *b = new Node { 3, nullptr };
Node *a = new Node { 2, b };
Node *start = new Node { 1, a };

And you should free the allocated memory before exiting the program.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • But why did this ran successfully on ideone https://ideone.com/IbPspC. Default value for such pointer is NULL? – Rohit Pal Jun 21 '17 at 14:25
  • @RohitPal It means as I wrote in my answer that the program has undefined behavior. – Vlad from Moscow Jun 21 '17 at 14:35
  • I'm getting `error: expected ';' at end of declaration Node *b = new Node {2, nullptr};`. same error for init of `a` and `start` node. – Rohit Pal Jun 21 '17 at 14:56
  • @RohitPal Maybe your compiler does not support this syntax of initialization. In this case write for example Node *b = new Node; b->data = 3; b->next = nullptr; or b->bext = NULL; – Vlad from Moscow Jun 21 '17 at 15:02