【发布时间】:2017-11-24 12:08:34
【问题描述】:
我有一个简单的 C++ 程序来遍历一个链表。
它在 ideone 中完美运行。
当我在我的 mac 终端中运行它时,它会引发分段错误。
当我从 traverse 函数中取消注释 //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;
}
【问题讨论】:
-
您在哪里/如何学习 C++?除了
cout这是 C 代码,而不是你应该如何使用 C++。 -
永远不应该在 C++ 中使用 malloc,除非您要维护一些从 C 移植的代码。
-
不包括
。不要在 C++ 中使用 malloc。 -
获取其中一个books。
标签: c++ linked-list segmentation-fault singly-linked-list