I wonder why the two values of int don't validate the if condition even if it is true. printf shows both of them are equal.
Is buffer overflow able to affect the behavior of if conditions,corrupting other code sections behavior.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
srand(time(NULL));
char instring[2]; // when this increases somehow I get the right behavior
int inint;
int guess;
guess = rand() % 127;
inint = ~guess;
printf("%i\n", guess); //testing with printf()
while (guess != inint) {
printf("Guess Number\r\n");
gets(instring);
inint = atoi(instring);
printf("%i\n", inint);
if (inint > guess) {
printf("%i\n", inint);
puts("too high");
} else if (guess > inint) {
puts("too low");
} else {
puts("right");
}
}
return 0;
}
The problem is indeed here.
Now let's think about this line.
Let's say you type
10
and hit enter. What will go intoinstring
is three bytes.1
0
instring
can only hold two bytes, butgets
will shove (at least) three in anyway. That extra byte will overflow into adjacent memory corrupting some other variable's memory causing some bizarre bug.And that's why making
instring
large enough to hold the result fromgets
fixes the program.To avoid this when working with strings, use functions which limit themselves to the memory available. In this case
fgets
.That will limit itself to only reading as much as it can fit into
instring
.In general, don't get stingy with memory to read input. A common practice is to allocate one large buffer for reading input, 1024 is good, and reuse that buffer just for reading input. The data is copied out of it to more appropriately sized memory, which
atoi
effectively does for you.