c++ - 释放动态内存时出现 C++ 错误
问题描述
错误 - 对象 0x7ffeefbff360 的 *** 错误:未分配被释放的指针。
我理解使用向量更好,但我们的教授希望我们以这种方式使用它。
我的 unwrap 函数在我想释放内存的地方出现错误,当我想使用显示函数中的 for 循环打印模式时,它会给我一个内存中的垃圾值,而不是打印出模式本身。我在 wrap 函数中使用 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];
的指针(并且您因为之前完成的分配丢失而导致内存泄漏)
后来在unwrap:
delete[] theGift.m_wrap[i].m_pattern;
您尝试删除该无效指针。
实际上是wrap而不是:
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
for m_pattern而不是 char 数组,以及std::vector<Wrapping>
for m_wrap而不是Wrapping数组。这简化了很多,不new
也delete
推荐阅读
- android - 在奥利奥中显示粉红色的导航抽屉
- javascript - 通过 Grafana 数据源插件的路由进行数据源身份验证
- angular - 角度 2 4 5 - 无法读取未定义角度 5 的属性“名称”
- angular - 动态提供服务到组件角度 2
- c# - 用户控制 BringToFront() 事件?
- java - 通过使用多种方法,找到具有给定坐标的三角形的周长
- sql - 如果计数为 0 或未找到行,则返回每个 Select Case 选项的结果
- typescript - typescript 管理 REST 调用和回调
- c# - 使用 pdfSharp 展平 AcroForm 以减小文件大小
- node.js - Nodejs:如何避免循环内nodejs中的异步调用?