未分配被释放的指针,但看起来已分配
Pointer being freed was not allocated, but looks like it was
我在此代码中遇到类的析构函数问题。它说它从未被分配过,但它应该是,我自己从来没有删除过它。以下是代码片段:
#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 是字符串**,您只需要字符串 *
相关文章:
- std::vector的包装器,使数组的结构看起来像结构的数组
- 看起来is_nothrow_constructible_v()在MSVC中被破坏了,我错了吗
- 学习多线程C++:添加线程不会使执行速度更快,即使它看起来应该
- 尽管一切看起来都很好,但值不会交换
- 自制的上衣:看起来一样,但不完全相同
- 如何使它看起来像正在下的雪
- 如何用逗号分隔输出?如何改进此代码以使其看起来更体面?
- 我的代码看起来不错,但某些输入会导致不需要的输出
- 为什么这个结构的大小是 40,而它看起来应该是 12/24?
- 我需要将阵列样式的邻接矩阵转换为矢量样式(以使其看起来更好)
- 结构化绑定:当某些内容看起来像引用并且行为类似于引用,但它不是引用时
- 如何使QTextEdit看起来被禁用
- 在正确性或良好的代码结构方面,这种动态对象创建看起来如何
- 看起来如此主要的错误.cpp:(.text.startup+0xd6):未定义对"vtable for Counter"的引用?
- C 时间测量看起来太慢了
- 我应该如何使 std::filesystem 看起来符合 Visual Studio 2015 的标准
- 写入.ini文件 - SimpleIni SetValue 尽管看起来成功了,但什么也没做
- std::string 上的 substr 无法正常工作,因为存在一些不可见但看起来像空格的字符
- 使标题看起来像它们在不同的文件夹中
- 未分配被释放的指针,但看起来已分配