变量周围的堆栈已损坏

Stack around the variable was corrupted

本文关键字:已损坏 堆栈 周围 变量      更新时间:2023-10-16

我有一个函数,它会循环直到键入正确的y,n答案,但在选择结束时,我会得到错误:

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

我在谷歌上看了一眼,真的找不到任何关于这个错误的重温答案,我的代码如下:

    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 againn";
    Beep (600,100);
    loop=0;                                                                                     //loop is zero, while loop continues.
    }
}
}

谢谢Houlahan。

之所以会发生这种情况,是因为YESNO是一个字符数组,而cin >> YESNO;正在向该数组写入NULL终止符。

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

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

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