变量周围的堆栈已损坏

时间:2012-03-06 19:52:35

标签: c++ visual-c++-2008

我有一个函数循环,直到正确的y,n回答是键入的但是在选择的最后我得到错误:

Time Check Failure #2 - Stack around the variable 'YESNO' was corrupted.

我看过google并且无法找到任何对此错误的重要答案我的代码如下:

    void Mesh_equations(float a,float b,float c,float d,float e,float f){

    char YESNO[1];                                                                                  //define variables.
    int loop=0;                                                                                 //loop set to zero.
    while(loop==0){                                                                             //while loop initiated whilst loop is equal to zero.
    cout <<"\nDo you want to display your coefficients for the mesh equations...(y/n)?";
    cin>>YESNO;                                                                                 //prompt and cin.
    if ( YESNO[0] == 'Y' || YESNO[0] == 'y'){                                                           //if cin is 'Y' or 'y'
        system("CLS");
        cout<<"Loop One:\n(" <<a <<")" <<"Ix + (" <<b <<")" <<"Iy = (" <<e <<")" <<endl
            <<"Loop Two:\n("  <<c <<")" <<"Ix + (" <<d <<")" <<"Iy = (" <<f <<")" <<endl<<endl
            <<setw(5)<<"  Where ;\n"
            <<setw(5)<<"A ="<<a<<endl 
            <<setw(5)<<"B ="<<b<<endl 
            <<setw(5)<<"C ="<<c<<endl
            <<setw(5)<<"D ="<<d<<endl
            <<setw(5)<<"E ="<<e<<endl                                                           ////set the field width to 5 characters.
            <<setw(5)<<"F ="<<f <<endl<<endl;                                                   //display.
        loop=1;                                                                                 //loop is 1, while loop passed.
        system("pause");
    }
    else if( YESNO[0] == 'N' || YESNO[0] == 'n'){                                                       //if 'N' or 'n', while loop passed.
    loop=1;
    }
    else{                                                                                       //if neither y or n is enterred input must be incorrect.
    cout <<"bad answer, try again\n";
    Beep (600,100);
    loop=0;                                                                                     //loop is zero, while loop continues.
    }
}
}

由于 Houlahan。

3 个答案:

答案 0 :(得分:4)

这种情况正在发生,因为YESNO是一个字符数组,而cin >> YESNO;正在为此数组写一个NULL终止符。

将YESNO的声明更改为char YESNO;,并删除数组运算符,您就可以了。

答案 1 :(得分:2)

如果数组元素被分配到数组的边界之外,那么在运行时它会显示消息“变量周围的堆栈已损坏”。因此,要解决此问题,请确保分配的数组大小和分配给它的值。

答案 2 :(得分:1)

使YESNO变大,即10个字符而不是1个。在数组中的最后一个允许位置之后放置空字符,这是错误的原因。