[释放动态内存的C ++错误

问题描述 投票:-2回答:1

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

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

我的拆包函数在我要释放内存的地方给了我错误,也当我想在display函数中使用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的错误:未分配指针。我了解使用向量更好,但是我们的教授希望我们以这种方式使用它。我的拆包函数给了我...

c++
1个回答
3
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.