I have the following class:
class Patient {
public:
Patient(int x);
~Patient();
private:
int* RP;
};
Patient::Patient(int x) { RP = new int [x]; }
Patient::~Patient() { delete [] RP; }
I create an instance of this class on the stack as follows:
void f() { Patient p(10); }
Now, when f()
returns, I get a "double free or corruption" error, which signals to me that something is attempted to be deleted more than once. But I don't understand why that would be so. The space for the array is created on the heap, and just because the function from inside which the space was allocated returns, I wouldn't expect the space to be reclaimed.
I thought that if I allocate space on the heap (using the new
keyword), then the only way to reclaim that space is to use the delete keyword. Help!
As requested, here is the actual code (slightly abridged for brevity's sake)
Here's the full class definition (split across a .cpp
and .h
file, but shown together):
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
}
Next, the function where the above class is used. The following function is called directly from main()
and passed a Policy
object which is completely independent and separate from the Patient
class:
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