[Solved] C strings behavior, and atoi function


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.

4

solved C strings behavior, and atoi function