遍历链表时出现分段错误

Getting Segmentation fault while traversing linked list

我有一个简单的 C++ 程序来遍历链表。 它 运行 完全符合 ideone 。 当我 运行 在我的 mac 终端中使用它时,它会抛出分段错误。 当我从遍历函数中取消注释 //printf("Node"); 行时,它 运行 是完美的。我无法理解这种行为。

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

你忘记了这条语句

b->next = nullptr;

否则,由于函数中 while 语句中的条件,程序具有未定义的行为 traverseLinkedList

while(start)

请注意,在 C++ 中您应该使用运算符 new 而不是 C 函数 malloc

例如

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

并且您应该在退出程序之前释放分配的内存。