Thursday 26 October 2017

c++ - double free or corruption with dynamic arrays

itemprop="text">

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

#include
#include

#include
#include

#include

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

};


Answer




All your allocations are new
...[]
, so all deletes must be delete []
...
.



delete []
testScore;
delete [] maxScore;
delete []
gpa;



Also
your code only allocates one element for testscore and maxscore but you keep writing
elements into the Array until the user enters -1. That means you will very likely write
over the end of the buffer.



You should get rid
of your raw pointers and use STL containers like std::vector.
With these you can easily add elements to the end without having to reallocate
yourself.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...