繁体   English   中英

程序可以在Debug中正常运行,但不能在Release中正常运行

[英]Program works fine in Debug, but not in Release

我做了一个井字游戏,效果很好。 最近,我决定添加一个重置游戏功能。 这是我接受用户输入的部分

void playerMove() //Gets the player move and updates the box variables
{
    int boxnumber;
    while(1)      //Set's loop if the player enters a invalid input
    {
       cout << "\n Player " << player << "'s turn!(Press 0 to reset the game!): ";
       cin >> boxnumber;
       if(box[boxnumber-1] == 'X' || box[boxnumber-1] == 'O' || boxnumber > 9 || boxnumber < 0) // Checks if the input is valid or not
       {
           system("CLS");//If invalid, show error and loop back to start to get new input
           displayBoard();
           cout << "\n Invalid Input! Try again!\n";

       }else if(boxnumber == 0)
       {
           refreshGame();
           displayBoard();
       }else
       {
           box[boxnumber-1] = player;//If inputs are fine, set the box variable's and break out of loop!
           break;
       }
    }

}

现在,在调试模式下,当我按0时,一切运行良好,并且游戏已重置,但是在发布版本中,当我按0时,它给了我“无效输入!请重试!”

我尝试过的没用的东西:-重建整个发行和调试版本。 -制作一个新项目并复制粘贴我的代码。 同样的事情,调试工作,发布没有。

对于任何想知道的人,我正在使用code :: blocks IDE。 编译器是GNU GCC。 谢谢您的帮助! :)

您有未定义的行为

在“ first”中, if您具有box[boxnumber-1] ,那么当您输入0 (如您在问题中所述)时,您正在尝试访问索引为-1元素。 那是UB,因为您正在读取“无效”内存。

您应该先检查0 (也要检查负数)。

if语句中,将范围检查放在值检查的前面。 也就是说,改变

if(box[boxnumber-1] == 'X' || box[boxnumber-1] == 'O' || boxnumber > 9 || boxnumber < 0)

if(boxnumber < 0 || box number > 9 || box[boxnumber-1] == 'X' || box[boxnumber-1] == 'O')

这利用了短路的优势:如果输入值小于0或大于9,则将不执行值检查。 这样可以避免检查box[10]无效内容。

仍然存在一个问题:如果用户输入0,则此代码将愉快地选中box[-1] ,这也超出了范围。 为了消除这一点,请将if语句的分支移动到该部分的前面,该语句测试box number == 0

if (box number == 0)
    // whatever
else if (box[boxnumber-1] == 'X' || box[boxnumber-1] == 'O' || boxnumber > 9 || boxnumber < 0)
    // whatever else

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM