【问题标题】:Getting Segmentation fault while traversing linked list遍历链表时出现分段错误
【发布时间】: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


【解决方案1】:

你忘了这句话

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

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

【讨论】:

  • 但是为什么在 ideone ideone.com/IbPspC 上运行成功。此类指针的默认值为 NULL?
  • @RohitPal 这意味着正如我在回答中所写的那样,该程序具有未定义的行为。
  • 我收到了error: expected ';' at end of declaration Node *b = new Node {2, nullptr};astart 节点的 init 相同的错误。
  • @RohitPal 也许你的编译器不支持这种初始化语法。在这种情况下,例如写 Node *b = new Node; b->数据= 3; b->下一个 = nullptr;或 b->bext = NULL;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多