Search code examples
cstringatoigets

C strings behavior, and atoi function


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;
  }

Solution

  • The problem is indeed here.

    char instring[2];
    

    Now let's think about this line.

    gets(instring);
    

    Let's say you type 10 and hit enter. What will go into instring is three bytes.

    1. 1
    2. 0
    3. A terminating null.

    instring can only hold two bytes, but gets 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 from gets fixes the program.

    To avoid this when working with strings, use functions which limit themselves to the memory available. In this case fgets.

    fgets(instring, sizeof(instring), stdin);
    

    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.