There is an error in your initialization to iii
, where the constant provided does not fit in int
.
GCC will diagnose this issue if you enable -pedantic
. From the documentation:
-Wpedantic
-pedantic
Issue all the warnings demanded by strict ISO C and ISO C++; reject all programs that use forbidden extensions, and some other programs that do not follow ISO C and ISO C++. For ISO C, follows the version of the ISO C standard specified by any -std option used.
When doing so, I get the error:
.code.tio.c: In function ‘main’:
.code.tio.c:7:15: error: overflow in conversion from ‘long int’ to ‘int’ changes value from ‘2147483650’ to ‘-2147483646’ [-Werror=overflow]
int iii = 2147483650;
^~~~~~~~~~
cc1: all warnings being treated as errors
Try it online!
Other problems
Arithmetic leading to signed integer overflow
The arithmetic operation i+1
triggers signed integer overflow, which has undefined behavior, so the compiler is free to do whatever it wants with that code.
Note that both operands to the +
operator have type int
, so if any result is generated, it would be an int
. However, since signed integer overflow is undefined, no result may be generated (e.g., the program could just halt), or a random result may be generated, or some other overflow behavior may occur that matches your observation.
In the general case, there isn't any way for the compiler to know if any particular operation will actually cause overflow. In this case, static code analysis may have revealed it. I believe GCC does perform some rudimentary static code analysis, but it is not required to identify every instance of undefined behavior.
Using sprintf
instead of snprintf
While it is safe to use sprintf
in your particular context, it is generally preferable to use snprintf
to guard against buffer overflow exploits. snprintf
simply needs an extra parameter to indicate the size of the buffer, and it will NUL
terminate the string for you.