2016-09-30 86 views
0

我正在用C++編寫一個簡單的應用程序,用來計算總和的頻率(即當你擲骰子時)。程序完全運行,它甚至產生了正確的結果,但是在執行結束時,Windows告訴我程序停止工作。C++程序完全執行,但最終破壞?

我正在使用Dev-Cpp 5.11和TDM-GCC 4.9.2 32位版本編譯器來創建和編譯下面的代碼。

#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; 
} 
+2

警告:您正在使用可變長度數組('val [n]'和'frq [t]')。這些是非標準的語法,容易導致堆棧溢出。 – user4581301

+1

另請注意:使用字母表變量命名方案對試圖調試代碼的人來說是一種抑制措施。一路平安。 – user4581301

回答

1

環路while(val[pos] >= r){...可保持循環,直到已經pos大大超過n,這是val[]大小,從而寫入零越過數組的末尾。這是災難性的。您需要執行如下操作:while(pos < n && val[pos] >= r){...

+0

這就是解決方案!謝謝。但是,這留下了一個問題,如果while循環導致問題,那麼爲什麼Windows在檢測到錯誤之後纔會檢測到錯誤? – McGeek07

+0

由於Windows並不經常檢查你的程序,以確保它正常運行。你的數組駐留在堆棧中,所以你可能會損壞你的堆棧框架,它包含你的'main()'函數返回到操作系統的返回地址。所以,只有當main()返回時,整個事情纔會失控。 –