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