简体   繁体   English

处理输入时意外冻结

[英]unexpected freeze while handling input

I've been trying to handle multiple functions which the user can select from, but for some reason, unexpected input isn't causing the developed reaction, freezing instead. 我一直在尝试处理用户可以选择的多个功能,但是由于某些原因,意外的输入不会引起开发的反应,而是冻结。

int main(){
    int done = 0, isModeValid = 1;
    char nextMode[15], *options[] = {"quit",  "test", "getASCII"};

    while(done == 0){
        cls();
        isModeValid = 0;
        text(1);
        currentOptions(options);
        gets(nextMode);
        int i = 0;
        for(i = 0; i < (sizeof(options)); i++){
            if(strcmp(nextMode, options[i]) == 0){
                 done = runMode(i);
                 break;
            }
            //Error seems to happen after this point
            if(strcmp(nextMode, options[i]) != 0 && i == sizeof(options)){
                cls();
                text(3);
                Sleep(750);
            }
        }
    }
    return 0;
}
void cls(){
    system("cls");
}

You are invoking undefined behaviour. 您正在调用未定义的行为。 sizeof yields the size of the argument in bytes / char s, not the length of the array. sizeof产生参数的大小(以字节 / char单位),而不是数组的长度 So you are iterating over more elements than the array actually contains and try to access elements past its bounds. 因此,您要遍历比数组实际包含的元素更多的元素,并尝试访问超出其边界的元素。

Use sizeof(options) / sizeof(options[0]) to get the length independent from the type of each entry. 使用sizeof(options) / sizeof(options[0])获得独立于每个条目类型的长度。

Note: Declaring the array static would make its allocation and initialization before main is called. 注意:声明数组为static将在调用main之前对其进行分配和初始化。 Your current version will do that each time the function is called. 您的当前版本将在每次调用该函数时执行该操作。 While uncritical for main , it will be significant for other functions which are called more than once. 尽管对main并不重要,但对于不止一次被调用的其他功能而言,它却具有重要意义。

To get the number strings in options , you need (sizeof(options)/sizeof(options[0])) , not just sizeof(options) ... so your for loop is looping too many times, and you're accessing out of bounds. 要获取options的数字字符串,您需要(sizeof(options)/sizeof(options[0])) ,而不仅仅是sizeof(options) ...因此,您的for循环循环了很多次,并且您正在访问范围。

Also, your second if never executes because i will never get to sizeof(options) . 另外,您的第二个命令if永远不会执行,因为i永远也不会进入sizeof(options)

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

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