C++ 代码编译时没有错误,但在运行时会出现“分段错误”
c++ code compiles without errors but gives a `Segmentation fault` while running
我无法理解我的问题。我有文件:
/*主要。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 还不够好吗?
问候,维尔纳
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 我是如何在这段代码中出现分段错误的
- 创建结构的数组时遇到分段错误
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 在 c++ 中实现 Trie 时出现分段错误
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 为什么我遇到分段错误?
- 实例化对象时如何修复分段故障错误
- 基本阵列操作中的分段故障错误
- 从void *强制转换会产生分段冲突错误
- 给出分段故障错误的c++ LCA程序
- 分段故障错误(信号名称:SIGSEGV)的原因是什么,以及如何查找/修复它