【问题标题】:C++ Program executes completely, but breaks at the end?C++程序完全执行,但最后中断?
【发布时间】:2016-09-30 23:15:30
【问题描述】:

我正在用 c++ 编写一个简单的应用程序,旨在计算和的频率(即当你掷骰子时)。该程序完全运行,它甚至产生了正确的结果,但在它执行的最后,Windows 告诉我程序停止工作。

我正在使用 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;   
}

【问题讨论】:

  • 警告:您正在使用可变长度数组(val[n]frq[t])。这些是非标准语法,容易导致堆栈溢出。
  • 另请注意:使用字母汤变量命名方案不利于尝试调试代码的人。再见。

标签: c++


【解决方案1】:

循环while(val[pos] &gt;= r){... 可能会一直循环,直到pos 远远超过n,这是val[] 的大小,因此在数组末尾写入零。那是灾难性的。你需要做类似while(pos &lt; n &amp;&amp; val[pos] &gt;= r){...

【讨论】:

  • 这就是解决方案!谢谢你。但是,这确实留下了一个问题,如果 while 循环导致问题,那么为什么 Windows 直到执行完成后才检测到错误?
  • 因为 windows 不会不断检查您的程序以确保其正常运行。您的数组驻留在堆栈中,因此您可能正在破坏堆栈帧,其中包含您的main() 函数将返回到操作系统的返回地址。所以,只有当main() 返回时,整个事情才会变得混乱。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-12
  • 2014-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多