为什么我无法使用 "delete" 关键字回收动态分配的内存?
Why can't I reclaim my dynamically allocated memory using the "delete" keyword?
我有以下类:
class Patient {
public:
Patient(int x);
~Patient();
private:
int* RP;
};
Patient::Patient(int x) { RP = new int [x]; }
Patient::~Patient() { delete [] RP; }
我在堆栈上创建此类的实例,如下所示:
void f() { Patient p(10); }
现在,当f()
返回时,我收到"双重释放或损坏"错误,这向我发出信号,表明某些内容尝试多次删除。但我不明白为什么会这样。 数组的空间是在堆上创建的,仅仅因为内部分配空间的函数返回,我不希望回收空间。
我认为如果我在堆上分配空间(使用 new
关键字),那么回收该空间的唯一方法是使用 delete 关键字。帮助!
根据要求,这是实际代码(为简洁起见略有删节)
下面是完整的类定义(拆分为.cpp
和.h
文件,但一起显示):
class Patient {
public:
Patient(int numDecisionEpochs);
~Patient();
void recordRP(const int& age, const bool& t);
void recordBiopsy(const int& age, const int& result);
void recordPSA(const int& age, const double& level);
void recordPSA(const int& age);
private:
int* RP;
int* Biopsy;
double* PSA;
};
Patient::Patient(int numDecisionEpochs) {
RP = new int [numDecisionEpochs];
Biopsy = new int [numDecisionEpochs];
PSA = new double [numDecisionEpochs];
}
Patient::~Patient() {
delete[] RP;
}
void Patient::recordRP(const int& age, const bool& t) {
if(t)
RP[age-1] = 1; // RP either yes (1) or no (0)
else
RP[age-1] = 0;
}
void Patient::recordBiopsy(const int& age, const int& result) {
switch(result)
{
case 0:
case 1:
case 2:
case 3:
case 4:
Biopsy[age-1]=result; // only permit results 0,1,2,3,4
break;
default:
cerr << "Invalid biopsy result (" << result << ") at age " << age << "!n";
}
}
void Patient::recordPSA(const int& age, const double& level) {
PSA[age-1] = level; // record PSA volume
}
void Patient::recordPSA(const int& age) {
PSA[age-1] = -1; // symbol for no screening during epoch
}
接下来,使用上述类的函数。 以下函数直接从main()
调用,并传递一个完全独立且独立于Patient
类的Policy
对象:
void simulate1(Policy& P)
{
// ...
Patient patient(260);
for(int idx=0; idx<(P.size); idx++)
{
while(state != 9) // while patient not dead
{
// ...
patient.recordPSA(age,PSA);
// ...
patient.recordPSA(age);
// ...
patient.recordBiopsy(age,biopsyResult);
// ...
patient.recordRP(age,true);
// ...
patient.recordRP(age,false);
// ...
} // end patient (while loop)
} // end sample (for loop)
} // end function
你违反了三法则(或者对于 C++11,五法则)。您需要一个复制构造函数和复制赋值运算符来执行指针的深层复制。当然,由于您不跟踪所分配数组的大小,因此如果不引入第二个数据成员,这是不可能的。
这不会直接回答您的问题,但也请考虑使用 std::vector。
任何record...
方法中都没有边界检查年龄。因此,如果示例中的年龄恰好大于260
或小于0
,您将写越RP
或Biopsy
或PSA
的界限。这直接导致"双重释放或损坏"错误。
相关文章:
- 删除类成员的动态分配内存的最佳方法是什么
- 如果您为类的一个对象动态分配内存作为参数,会发生什么
- 为浮点数组动态分配内存
- 包含动态分配内存作为值的映射的取消定位速度有多快?
- STD分配器是否会在堆上动态分配内存?它可以安全地删除内存吗?
- 如何为const char double指针(使用新的)动态分配内存
- 在动态分配内存的同时,使用指定尺寸
- 动态分配内存
- 如何在我指向的安德烈斯上动态分配内存?
- 为什么C 没有方便的方式来为多维数组动态分配内存
- 当动态分配内存时警告
- 为结构动态分配内存
- 动态分配内存,用于存储使用 WinHttpReadData 下载的 HTML 源代码
- 如何在C++中为灵活阵列动态分配内存
- 从C++中的文件读取时动态分配内存到结构
- 在c++中的赋值运算符重载方法中删除旧的动态分配内存
- 在类方法中使用新运算符动态分配内存的寿命和范围是多少
- 以C++为单位的动态分配内存的初始值
- 虚拟析构函数:如果基类动态分配内存,基类中是否需要它
- 如何在 c++ 中使用 2-D 固定数组为 4-D 数组动态分配内存