C++ 代码编译时没有错误,但在运行时会出现“分段错误”

c++ code compiles without errors but gives a `Segmentation fault` while running

本文关键字:分段 分段错误 错误 运行时 编译 代码 有错误 C++      更新时间:2023-10-16

我无法理解我的问题。我有文件:

/*主要。C */

#include <iostream>
#include "point.h"
using namespace std;
int main()
{
    Point p_default;
    p_default.print();
    Point p_equal(2.5);
    p_equal.print();
    Point p_full(1.23, 2.4, 0.18);
    p_full.print();
    return 0;
}

/* point.h */

#include <iostream>
using namespace std;
class Point {
    double x, y, z;
    double* arr;
public:
    // constructors
    Point (); // default
    Point (double); // equal arguments 
    Point (double _x, double _y, double _z); // standard
    // destructor
    ~Point ();
    // print function
    void print () const;
};

/*点。C */

#include <iostream>
#include "point.h"
using namespace std;
// constructors
Point::Point () : Point(0.0) {}; // default - zero initialised
Point::Point (double _c) : Point(_c, _c, _c) {}; // equal arguments 
// standard constructor
Point::Point (double _x, double _y, double _z = 0.0)
: x(_x), y(_y), z(_z) {
    double* arr = nullptr;
    arr = new double[3];
    *arr = x;
    *(arr + 1) = y;
    *(arr + 2) = z;
};
// destructor
Point::~Point () {
    delete[] arr;
};
// print function
void Point::print () const {
    cout << "Point(" << x << ", " << y << ", " << z << ")" << endl;
};

我使用以下命令编译我的项目:g++ -Wall -std=c++11 main.C point.C -o main .它的编译没有任何错误或警告,但是当我使用 ./main 运行它时,它会正确打印所有内容,最后给了我Segmentation fault

Point(0, 0, 0)
Point(2.5, 2.5, 2.5)
Point(1.23, 2.4, 0.18)
Segmentation fault (core dumped)

我认为它与我的析构函数有关,但无法理解问题出在哪里。

问题是,你从不初始化你的 Point 类的数据成员"arr"。这

double* arr = nullptr;
arr = new double[3];

在构造函数中创建一个本地指针"arr"并初始化本地指针,但不初始化类成员"arr"。当您尝试删除析构函数中的"arr"时,您尝试删除类的"arr",该类从未被分配和初始化。

// standard constructor
Point::Point (double _x, double _y, double _z = 0.0)
: x(_x), y(_y), z(_z) {
    // This is local, yet you are deleting the non-initialized member
    // in your destructor!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    double* arr = nullptr;
    arr = new double[3];
    *arr = x;
    *(arr + 1) = y;
    *(arr + 2) = z;
};

请参阅我在代码中的评论...

除此之外,您的代码还存在许多问题:

  • 默认复制构造函数是不够的。
  • 下划线作为为标准保留的前缀。
  • 使用 std 容器(例如向量或数组)而不是尝试管理记住自己。
  • 为什么首先要有一个数组?成员变量 x,y,z 还不够好吗?

问候,维尔纳