释放动态内存时C++错误

C++ errors with releasing Dynamic memory

本文关键字:C++ 错误 内存 动态 释放      更新时间:2023-10-16

错误 - 对象 0x7ffeefbff360 的 *** 错误:未分配正在释放的指针。

我知道使用向量更好,但是我们的教授希望我们以这种方式使用它。

我的解包函数在我想释放内存的地方给了我错误,当我想在显示函数中使用 for 循环打印图案时,它会从内存中给我一个垃圾值,而不是打印出图案本身。我在包装函数中使用 cout 进行了测试,它在那里工作,但在我的显示函数中不起作用。

bool wrap(Gift& theGift){
if (theGift.m_wrap == nullptr) {
cout << "Wrapping gifts..." << endl;
do {
cout << "Enter the number of wrapping layers for the Gift: ";
cin >> theGift.m_wrapLayers;
}while ((theGift.m_wrapLayers <= 0) && cout << "Layers at minimum must be 1, try again." << endl);
theGift.m_wrap = new Wrapping[theGift.m_wrapLayers];
char buffer[100];
int patternLength;
for (int i = 0; i < theGift.m_wrapLayers; i++) {
cout << "Enter wrapping pattern #" << i + 1 << ": ";
cin >> buffer;
patternLength = (unsigned)strlen(buffer);
theGift.m_wrap[i].m_pattern = new char[patternLength + 1];
theGift.m_wrap[i].m_pattern = buffer;
cout << theGift.m_wrap[i].m_pattern << endl;
}
return true;
}else {
cout << "Gift is already wrapped!" << endl;
return false;
}
}
bool unwrap(Gift& theGift){
if (theGift.m_wrap != nullptr) {
cout << "Gift being unwrapped." << endl;
for (int i = 0; i < theGift.m_wrapLayers; i++) {
delete[] theGift.m_wrap[i].m_pattern;
theGift.m_wrap[i].m_pattern = nullptr;
}
delete[] theGift.m_wrap;
theGift.m_wrap = nullptr;
return true;
}else{
cout << "Gift isn't wrapped! Cannot unwrap." << endl;
return false;
}
}
void display(Gift& theGift){
cout << "Gift Details: " << endl;
cout << " Description: " << theGift.m_description << endl;
cout << "       Price: " << theGift.m_price << endl;
cout << "       Units: " << theGift.m_units << endl;
cout << "Wrap Layers: " << theGift.m_wrapLayers << endl;
for (int i = 0 ; i < theGift.m_wrapLayers; i++) {
cout << "Wrap #" << i + 1 << " ->" << theGift.m_wrap[i].m_pattern << endl;
}
}

错误 - 对象 0x7ffeefbff360 的 *** 错误:未分配正在释放的指针。

包装中 :

char buffer[100];
...
theGift.m_wrap[i].m_pattern = buffer;

in-out 参数中保存theGift指向本地数组缓冲区的指针(并且您之前在theGift.m_wrap[i].m_pattern = new char[patternLength + 1];中完成的分配丢失了内存泄漏(

后来在解包中:

delete[] theGift.m_wrap[i].m_pattern;

尝试删除该无效指针。

事实上是包装而不是:

你想做的

theGift.m_wrap[i].m_pattern = new char[patternLength + 1];
theGift.m_wrap[i].m_pattern = buffer;
theGift.m_wrap[i].m_pattern = new char[patternLength + 1];
strcpy(theGift.m_wrap[i].m_pattern, buffer);

请注意,您还可以将std::string用于m_pattern而不是字符数组,以及将std::vector<Wrapping>用于m_wrap而不是包装数组。这简化了很多,没有new也没有delete