未分配被释放的指针,但看起来已分配

Pointer being freed was not allocated, but looks like it was

本文关键字:分配 看起来 释放 指针      更新时间:2023-10-16

我在此代码中遇到类的析构函数问题。它说它从未被分配过,但它应该是,我自己从来没有删除过它。以下是代码片段:

#ifdef UNIT_TESTING_CONSTRUCTORS
//Test Constructors
cout << "Test constructors nConctructor 1:n";
Doctor testDoc1;
testDoc1.displayPatientArray();
cout << "nConstructor 2:n";
Doctor testDoc2(2);
testDoc2.displayPatientArray();
cout << "nConstructor 3:n";
//Implement more test cases below:
Doctor testDoc3("Wesley Cates");
testDoc3.displayPatientArray();
cout << "nConstructor 4:n";
Doctor testDoc4("Baylor Bishop", 3);
testDoc4.displayPatientArray();
#endif

Doctor::Doctor() : doctorName("need a name."), patientArraySize(100), numOfPatient(0) {
//Create a dynamic array for patients below:
//stringPtr_t* pArray;
stringPtr_t* patientArray;
patientArray = new stringPtr_t[patientArraySize];

和类:

typedef unsigned short ushort_t;
typedef string* stringPtr_t;
class Doctor {
private:
string doctorName;
stringPtr_t patientArray;
ushort_t patientArraySize;
ushort_t numOfPatient;
public:
Doctor();
Doctor(ushort_t patientArrayCapacity);
Doctor(string docName);
Doctor(string docName, ushort_t patientArrayCapacity);
bool addPatient(string patientName);
void displayPatientArray();
void resizePatientArray(ushort_t newArraySize);
string getDoctorName() const {return doctorName;}
ushort_t getNumOfPatient() const {return numOfPatient;}
ushort_t getArraySize() const {return patientArraySize;}
void setDoctorName(string docName) {doctorName.assign(docName);};
void emptyPatientArray() {numOfPatient = 0;}
Doctor& operator =(const Doctor& docSource);
~Doctor() {delete [] patientArray;}
};
您在

构造函数Doctor::Doctor()中初始化的数组是一个名为"patientArray"的局部变量,而不是您在析构函数中删除的类变量。

若要解决此问题,请将构造函数更改为以下内容:

Doctor::Doctor() : doctorName("need a name."), patientArraySize(100), numOfPatient(0) { // Create a dynamic array for patients below: // stringPtr_t* pArray; // Delete local variable declaration that was here: stringPtr_t* patientArray; // patientArray = new string[patientArraySize];

您正在使用typedef string* stringPtr_t; . 所以stringPtr_t变量已经是指针了。

所以无需使用stringPtr_t* patientArray;您只需使用stringPtr_t patientArray;

如果您使用的是 stringPtr_t* patientArray;,patientArray 是字符串**,您只需要字符串 *