【问题标题】:Exception thrown when deleting memory of heap memory删除堆内存的内存时抛出异常
【发布时间】:2022-01-07 14:06:24
【问题描述】:

我在以下代码中的 delete[] user; 语句中遇到异常。该代码是一个菜单系统,它必须将数据加载到vector,然后将内存分配给堆。请帮忙。

#include <fstream>
#include <iostream>
#include <crtdbg.h>
#include <vector>
#include <string>
#include <sstream>
#include "Userboard.h"

using namespace std;

int main()
{
    const int M_USER = 6;
    const int M_PASS = 7;
    const int M_SCORE = 2;
    int choice;
    vector<string>  player;
    fstream file("pinfo.txt");
    string line;
    while (getline(file, line)) {
        player.push_back(line);
    }
    const int NO_OF_PLAYERS = 20;
    Userboard* stPlayer[NO_OF_PLAYERS] ;
    string p;
    string u;
    char* key = new char[MAX_PASS];
    char* user = new char[MAX_USER];
    for (int i = 0; i < player.size(); i++) {
        int score;
        u = player[i].substr(0, M_USER);   
        stringstream ss;
        ss << player[i].substr(20, M_SCORE);
        ss >> score;
        p = player[i].substr(10, M_PASS);
        cout << " " << u << score << endl;      
        for (int a = 0; a < M_USER;a++) {
            user[a] = u[a];
        }
        
        for (int a = 0; a < M_PASS; a++) {
            key[a] = p[a];
        }
    }

    do
    {
        cout << "\n\n1) Exit\n\nChoose an option:";
        cin >> choice;
        switch (choice)
        {
            case 1:
                for (int i = 0; i < player.size(); i++) {
                    for (int a = 0; a < M_USER; a++) {
                        delete[] user;
                    }
                    for (int a = 0; a < M_PASS; a++) {
                        delete[] key;
                    }
                }
                return 0;
            default:
        }; 
    } while (choice != 1);
};

【问题讨论】:

  • 您是双重(三重、四重等)删除资源。这是不允许的。
  • 只有一个user,但你多次调用delete[] user;
  • 当您还使用std::string 时,我不明白为什么需要在堆上分配 C 字符串。这可能是对您想要的内容与您所写的内容的误解。
  • 'std::string' 也分配给 hep 内存吗?
  • 建议避免显式内存管理。您可以使用unique_ptrvectorstring 等。

标签: c++ exception heap-memory


【解决方案1】:

你是 new[]'ing keyuser 只有 1 次,所以你应该只 delete[] 1 次,而不是循环。

do
{
    cout << "\n\n1) Exit\n\nChoose an option:";
    cin >> choice;
    switch (choice)
    {
        case 1:
            delete[] user;
            delete[] key;
            return 0;
    }
} while (true);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-12
    • 1970-01-01
    • 2013-05-20
    相关资源
    最近更新 更多