c++ - 类中的分段错误
问题描述
#include <iostream>
using namespace std;
class Bucket{
public:
Bucket();
void setN(int n);
void setArrayb();
void storeArray(int s, int cc, int **A);
int showdata(int cc);
private:
int n_elements;
int *b;
};
Bucket :: Bucket(){
;
}
void Bucket :: setN(int n)
{
n_elements = n;
}
void Bucket :: setArrayb(){
int *b = new int [n_elements + 1];
}
void Bucket :: storeArray(int s, int cc, int **A){
cout << this -> n_elements;
if(cc <= n_elements){
this -> b[cc] = A[0][s];
}
}
int Bucket :: showdata(int cc){
return this -> b[cc];
}
int main(){
int n = 10;
int** A = new int*[1];
for (int i = 0 ; i < 1 ; i++){
A[i] = new int [n + 1];
}
Bucket B[n + 1];
A[0][3] = 6;
int fb = 10;
B[1].setN(fb) ;
B[1].setArrayb();
B[1].storeArray(3, 1, A);
cout << B[1].showdata(1);
}
我正在尝试用n桶为A完成桶排序。n_element是每个桶的数量,编译后是合法的。但是当我执行它时,它会导致分段错误。有人可以解释这段代码中发生了什么吗?
通过cygwin在linux环境下使用。
解决方案
您的问题是由于您对以下行在setArrayb
.
int *b = new int [n_elements + 1];
- 它初始化一个函数局部变量
b
。 - 它不对同名的成员变量做任何事情。
- 它泄漏内存。
当您访问成员变量b
in的元素时storeArray
,您访问的是一个未初始化的指针,这会导致未定义的行为。
将该行更改为
b = new int [n_elements + 1];
除非您需要在代码中管理动态分配的内存,否则请将您的类更改为使用std::vector<int>
.
如果您必须管理自己的记忆,请遵循“三法则”。
推荐阅读
- reactjs - 我什么时候应该在 reactjs 中使用 useRef 或 useState
- python - 屏蔽一个三维数组以执行分割
- javascript - 将 UTC 时间戳转换为可读格式
- c++ - 打开文件和系统功能总是失败?
- design-patterns - 事件同步
- powerbi - PowerBi 似乎失去了连接状态,具体取决于我选择的字段
- amazon-web-services - cloudwatch 日志订阅过滤器到 terraform 上的 kinesis
- c# - 如何从 .NET 3.5 C# 中的 Json 获取值?
- c# - 我正在关注教程,但遇到覆盖错误。无法弄清楚问题所在。CS0115
- python - 在数据框中查找具有 nan 值的列的重复子集