Help with Error Message: Stack around Variable was Corrupted

Once I run my program, I keep getting the error message: Run-Time Check Failure #2 - Stack around the variable 'numTimes' was corrupted. Would someone be able to explain to me what that error message means and how I would start to fix it. Any help is greatly appreciated.


#include <iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
void loadRandom666Array(int freq[], int numRolls);
bool printHistogram(int freqDist[], int numRolls);
const int MAX_SIZE = 16;

int main()
{
int numTimes, freq[MAX_SIZE], seed;

seed = time(0);
srand(seed);

cout<<"Enter how many times the dice should be rolled: ";
cin>> numTimes;

loadRandom666Array(freq,numTimes);
printHistogram(freq, numTimes);
}

void loadRandom666Array(int freq[], int numRolls)
{
int val1, val2, val3, sum;

for(int a = 0; a < MAX_SIZE; a++)
{
freq[a] = 0;
}

for(int b = 0; b < numRolls; b++)
{

val1 = (rand()%6)+1;

val2 = (rand()%6)+1;

val3 = (rand()%6)+1;

sum = val1 + val2 + val3;
freq[sum]++;
}
return;
}


bool printHistogram(int freqDist[], int numRolls)
{
int sum = 0;

for(int h = 0; h < MAX_SIZE; h++)
{
sum = sum + freqDist[h];
}

if(sum != numRolls)
{
cout<<"Error";
return false;
}
else
{
for(int rowcount = 3; rowcount < 19; rowcount++)
{
cout<<endl<<rowcount<<" | ";
for(int i = 0 ; i < MAX_SIZE; i++)
{
for(int j = 0 ; j < freqDist[i]*100 / numRolls; j++)
{
cout<<'*';
}

}

}
return true;
}
}
Last edited on
You are stepping out of bounds of your array:

1
2
3
4
5
6
7
8
val1 = (rand()%6)+1;

val2 = (rand()%6)+1;

val3 = (rand()%6)+1;

sum = val1 + val2 + val3;
freq[sum]++;


6+6+6 = 18
but the largest valid index for 'freq' is 15

Increase MAX_SIZE to 19 so that your array is large enough.
Hi

What are doing in the following loop, freq[sum]++; ??

cant sum be larger than 16 , I think it can be!

Your code has many bugs!

1
2
3
4
5
6
7
8
9
10
11
12
for(int b = 0; b < numRolls; b++)
{

val1 = (rand()%6)+1;

val2 = (rand()%6)+1;

val3 = (rand()%6)+1;

sum = val1 + val2 + val3;
freq[sum]++;
}
Topic archived. No new replies allowed.