Reputation: 23
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");
}
Upvotes: 0
Views: 48
Reputation: 12262
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.
Upvotes: 3
Reputation: 9375
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)
.
Upvotes: 0