为什么我无法使用 "delete" 关键字回收动态分配的内存?

Why can't I reclaim my dynamically allocated memory using the "delete" keyword?

本文关键字:动态分配 内存 关键字 delete 为什么      更新时间:2023-10-16

我有以下类:

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,您将写越RPBiopsyPSA的界限。这直接导致"双重释放或损坏"错误。