适用于Windows,但在Ubuntu上出现分段错误

Works on windows but gives Segmentation fault on Ubuntu

本文关键字:分段 错误 Ubuntu Windows 但在 适用于      更新时间:2023-10-16

所以我在这里的不同线程中看到了这种问题,但找不到这种情况所需的答案......

就像我在标题中提到的,我的代码在 Visual Studio 2013 上运行良好,没有内存泄漏或类似的东西,但是当通过 Ubuntu 的平台运行时,它会运行到调用复制构造函数的位置,然后在将第二个节点设置为新节点时停止,我尝试将该构造函数标题中"const"的位置切换为在函数之后或类型名称之后,然后它只是根本不起作用,我尝试更改函数的顺序,但什么也没做,我尝试以不同的方式调用复制构造函数,这也只是给出了相同的结果,我也尝试向我的练习老师展示这个,你可以猜到结果,因为我仍然在这里写这个线程:P

那我错过了什么?

下面的代码表示一个循环链表,每个节点中有 2 种数据类型:.hpp

#include <iostream>
#include <string>
using namespace std;
class MyLinkedList{
private:
    class Node{
    public:
        Node* next;
        Node* prev;
        string key;
        double data;
        Node(const string key, const double data)
        {
            this->next = this->prev = NULL;
            this->key = key;
            this->data = data;
        }
        Node(const Node* node)
        {
            this->next = this->prev = NULL;
            this->key = node->key;
            this->data = node->data;
        }
    };//END OF NODE
    Node* head;
    Node* tail;
public:
    MyLinkedList();
    void add(const string& key, const double& data);
    MyLinkedList(const MyLinkedList& MLL);
    ~MyLinkedList();
    bool empty();
    void printList();
    MyLinkedList& operator=(const MyLinkedList&);
    int remove(const string&);
    bool isInList(const string, double&);
    double sumList();
};

.cpp(部分(:

#include "MyLinkedList.hpp"
MyLinkedList::MyLinkedList(){
    head = tail = NULL;
}
void MyLinkedList::add(const string& key, const double& data){
    if (empty()){
        head = new Node(key, data);
        tail = head->next = head->prev = head;
        tail->next = tail->prev = head;
        return;
    }
    tail->next = new Node(key, data);//**(Segmentation fault HERE)**
    tail->next->prev = tail;
    tail = tail->next;
    tail->next = head;
    head->prev = tail;
}

MyLinkedList::MyLinkedList(const MyLinkedList& MLL){
    if (MLL.head == NULL){
        head = tail = NULL;
        return;
    }
    Node* N1 = MLL.head;
    do{
        add(N1->key, N1->data);//<--falls on the second time
        N1 = N1->next;
    } while (N1 != MLL.head);
}
bool MyLinkedList::empty(){
return head==NULL;
}
int main(){
    MyLinkedList A;
    A.add("key1", 1);
    A.printList();
    A.add("key4", 2);
    A.add("key3", 3);
    A.add("key4", 4);
    A.printList();
    cout << "sum: " << A.sumList() << endl;
    MyLinkedList A2(A);// <--Segmentation fault within.
    A2.printList();
}

您不像在默认构造函数中那样初始化复制构造函数中的指针,因此当您调用 add 时它们会悬空。做

MyLinkedList::MyLinkedList(const MyLinkedList& MLL) {
  head = tail = NULL;
  // Rest as before

几个旁注:由于您使用的是 MSVC 2013,因此具有(有限的(C++11 支持,您也可以编写

// nullptr is the typesafe C++11 way to write NULL
Node* head = nullptr;
Node* tail = nullptr;

在课堂上,再也不用担心了。另一个样式说明是,在 ctor init 列表中初始化数据成员可以说是更好的样式,而不是像这样在构造函数主体中初始化数据成员:

MyLinkedList::MyLinkedList(const MyLinkedList& MLL)
 : head(nullptr),
   tail(nullptr) {
  ...

因为这也适用于不可默认构造的成员,例如引用。