McGeek07 McGeek07 - 2 months ago 18
C++ Question

C++ Program executes completely, but breaks at the end?

I was writing a simple application in c++, designed to calculate frequencies of sums (i.e. when you roll dice). The program runs through completely, it even produces the correct results, but at the very end of it's execution Windows tells me that the program stopped working.

I am using Dev-Cpp 5.11 with the TDM-GCC 4.9.2 32-bit release compiler to create and compile the code that follows.

#include<iostream>
#include<limits>
#include<string>

using namespace std;

const int int_min = numeric_limits<int>::min(),
int_max = numeric_limits<int>::max();

int getint(string ln, int lower, int upper){
int input = 0;
cout << ln;
if(cin >> input && input >= lower && input <= upper){
cin.clear();
cin.ignore(80,'\n');
}else{
cout << "ERR:\tINVALID\nDesc:\t";
if(cin.good() && (input <= lower || input >= upper))
cout << "OUT OF BOUNDS [" << lower << " <= val <= " << upper << "]";
else
cout << "NAN";
cout << "\n\n";
cin.clear();
cin.ignore(80,'\n');
return getint(ln,lower,upper);
}
return input;
}

int main(){
int
n = getint("Input(n) > ",1,int_max),
a = getint("Input(a) > ",0,int_max),
b = getint("Input(b) > ",a,int_max),
r = b - a + 1,
t = n * (r - 1) + 1;
int
pos = 0,
sum = 0,
val[n],
frq[t];

for(int i = 0; i < n; i++)
val[i] = 0;
for(int i = 0; i < t; i++)
frq[i] = 0;
while(pos < n){
pos = 0;
sum = 0;
for(int i = 0; i < n; i++)
sum += val[i];
frq[sum]++;
val[pos]++;
while(val[pos] >= r){
val[pos++] = 0;
if(pos <= n - 1)
val[pos]++;
}
}

for(int i = 0; i < t; i++){
cout << "frq(" << i + n << ")\t|\t" << frq[i] << endl;
}
return 0;
}

Answer

The loop while(val[pos] >= r){... may keep looping until pos has well exceeded n, which is the size of val[], thus writing zeros past the end of the array. That's disastrous. You need to do something like while(pos < n && val[pos] >= r){...