lundi 30 janvier 2017

double free or corruption with dynamic arrays

my problem today is with dynamic arrays. Every time I enter more then 2 test scores I get an error after I enter the 3rd max test score which says "* Error in `./a.out': double free or corruption (out): 0x09c2e028 * Aborted (core dumped)" Am I doing something wrong with the arrays? Or is there something I'm painfully missing?

The program is supposed to take an unlimited number of test scores and their respective max possible points (i.e. test score = 76 Max test score possible = 100) and turn those numbers into a GPA. I'be only included the class I'm using to create the GPA because the rest of the code isn't finished yet as I can't get past this part.

I have to use the dynamic arrays because it is for a school assignment.

Thanks for reading I hope someone can help me!

#include <iostream>
#include <string>
#include <cmath>
#include <math.h>
#include <iomanip>
#include <cassert>
using namespace std;
void programGreeting();

class testScores{
public:
    float testAverage(){
        int i = 0;
        float gpa2 = 0;
        int loopCountVar = 0;
        int size = 1;
        int size2 = 1;
        float *testScore = new float[size];
        float *maxScore = new float[size];
        while(testScore[i] != -1){
            i++;
            loopCountVar++;
            cout << "Enter test score #" << loopCountVar << endl;
            cin >> testScore[i];
            if(testScore[i] == -1){
                size = i;
            }
            assert(testScore[i] > -2);
        cout << "Enter max test score #" << loopCountVar << endl;
        cin >> maxScore[i];
        if(maxScore[i] == -1){
            size2 = i;
        }
        assert(maxScore[i] > -2);
        }
        float *gpa = new float[size];
        for(i = 1; i < size; i++){
            gpa[i] = testScore[i] / maxScore[i];
            cout << gpa[i] << " " << endl;
        }
        for(i = 1; i < size; i++){
            gpa2 += gpa[i];
        }
        for (i = 1; i < size; i++){
            cout << endl << testScore[i] << " " << endl;
        }
        for (i = 1; i < size2; i++){
            cout << endl << maxScore[i] << " ";
        }
        cout << endl << gpa2 << endl;
        cin >> size;
        delete testScore;
        delete [] maxScore;
        delete gpa;
        return 0;
    }       
};

Aucun commentaire:

Enregistrer un commentaire