【问题标题】:Pointer being freed was not allocated, but looks like it was被释放的指针未分配,但看起来是
【发布时间】:2014-04-03 23:26:41
【问题描述】:

我在这段代码中遇到了我的类的析构函数问题。就是说从来没有分配过,但它应该是,我自己从来没有删除过它。这是代码的sn-ps:

#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;}
};

【问题讨论】:

  • 你有缩进和写可读代码的问题吗?
  • 您的问题不清楚。请阅读How to Askhelp center 了解如何提问。
  • 如果您不提供minimal complete example,任何人都不太可能帮助您。
  • 这可能还不是问题,但您可能还需要一个复制构造函数(C++ 规则三)。

标签: c++ destructor dynamic-memory-allocation


【解决方案1】:

您在构造函数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];

【讨论】:

  • 它告诉我我必须做 *new 而不是 new。当我这样做时,它会导致同样的错误。我还缺少其他东西吗?
  • patientArray = 新字符串[patientArraySize];
【解决方案2】:

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

所以不需要使用stringPtr_t* patientArray;你可以使用stringPtr_t patientArray;

如果你使用stringPtr_t* patientArray;patientArraystring** 并且你只需要 string *

【讨论】:

  • 虽然这是真的,但这不是他所看到的错误的近因。
  • 你是对的,但这不是问题所在。类成员 patientArray 按原样基于 typedef 正确声明。构造函数中的局部变量声明错误地变成了指向指针的指针,但是,该声明一开始就不应该存在。
猜你喜欢
  • 1970-01-01
  • 2018-09-30
  • 2016-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-11
  • 2019-03-13
相关资源
最近更新 更多