Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
407 views
in Technique[技术] by (71.8m points)

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
", guess); //testing with printf()
    while (guess != inint) {
      printf("Guess Number
");
      gets(instring);
      inint = atoi(instring);
      printf("%i
", inint);

      if (inint > guess) {
        printf("%i
", inint);
        puts("too high");
      } else if (guess > inint) {
        puts("too low");
      } else {
        puts("right");
      }
    }
    return 0;
  }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...