r/C_Programming • u/No_Insurance_6436 • Sep 08 '26
Question How can printf() change unrelated uninitialized variable behavior?
So, I just fixed a strange bug. I have a loop that loops through a char array until it finds a null terminator.I had miswritten and overlooked this after deleting a second variable I was initializing in that loop. So I ended up with:
for (int i; text[i] != '\0'; i++){}
Which I have since fixed. However, curiously, this program was running with normal operation because of a printf() statement operating on completely unrelated data; i would initialize to 0 every time. Other assignments happened between this print and the errored line as well.
printf("ID: %u\n", tID);
It had to be placed at a specific spot for it to fix the bug, but it fixed it every time, so the bug went unnoticed until I was cleaning up.
But, how exactly would this happen? What does printf() do that would change initialized variable behavior, and why was it consistently initializing to 0?
The value of i would print to 21937 without the printf() and 0 with it.
View all comments
Show parent comment
1
u/flatfinger Sep 08 '26
Such a contract existed prior to the publication of C99, and earlier versions of the contract generally treated the notion of "indeterminate value" as being equivalent to "unspecified bit pattern". Indeed, even in C draft N1570, the glossary reads as follows:
A programmer who has no idea whether an implementation would treat a type as having trap representations would have no way of knowing whether an indeterminate value might be one. If every possible bit pattern an object might hold would represent a different specific defined value, however, nothing prior to C99 would have in any way suggested the possibility that an indeterminate value might behave in a manner inconsistent with any bit pattern the object's storage would be capable of holding.