首页 > 解决方案 > 释放动态内存时出现 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;

    }

}

标签: c++

解决方案


错误 - 对象 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::stringfor m_pattern而不是 char 数组,以及std::vector<Wrapping>for m_wrap而不是Wrapping数组。这简化了很多,不newdelete


推荐阅读