简体   繁体   中英

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. 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.

Note: Declaring the array static would make its allocation and initialization before main is called. 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.

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.

Also, your second if never executes because i will never get to sizeof(options) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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