我有簡單的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++。 – NathanOliver
不應該有任何理由在C++中使用malloc,除非您維護從C中移植的代碼。 – Lundin
不包含。 不要在C++中使用malloc。 –
2017-06-21 14:33:58