RedBeast88
RedBeast88

Reputation: 1

Exception thrown when deleting memory of heap memory

I am getting an exception thrown on the delete[] user; statement in the following code. The code is a menu system that must load data into a vector then allocate the memory to heap. Please help.

#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);
};

Upvotes: 0

Views: 148

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595827

You are new[]'ing key and user only 1 time, so you should delete[] them only 1 time, not in a loop at all.

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

Upvotes: 1

Related Questions