遍历链表时获取分段错误

时间:2017-06-21 14:13:31

标签: c++ linked-list segmentation-fault singly-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;
}

1 个答案:

答案 0 :(得分:3)

你忘了这句话

b->next = nullptr;

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

while(start)

考虑到在C ++中你应该使用运算符new而不是C函数malloc

例如

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

在退出程序之前,你应该释放已分配的内存。

相关问题