C strings behavior, and atoi function

好久不见. 提交于 2019-12-13 10:44:22

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/49850276/c-strings-behavior-and-atoi-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!