Why Adding printf Can Hide Segmentation Faults: A Debugging Tale
An amusing yet instructive narrative shows how a C program that crashes with a segmentation fault can appear to work after inserting a printf, explaining that uninitialized local variables contain leftover stack data and that debugging tools like GDB reveal the true cause.
A programmer named Zhang San encounters a segmentation fault when running a simple C program compiled with gcc -g test.c -o test and executed as ./test , which immediately crashes.
After a humorous "blessing" ritual, he adds a mysterious code snippet (shown in the original article) and recompiles; the program then runs without crashing, leading his colleagues to marvel at the "miraculous" fix.
The article then shifts to a technical explanation: the crash originates from an uninitialized local variable idx in function bar() . Because idx is never given a value, it contains whatever data was left on the stack by a previous call to fool() , where memset(array, 1, sizeof(array)) filled memory with the pattern 0x01, resulting in idx = 0x01010101 . This value causes an out‑of‑bounds write buf[idx] = 'A' , triggering the segmentation fault.
When a printf (or any other I/O call) is inserted before the faulty access, the stack layout changes: the call pushes additional data onto the stack, overwriting the residual value and effectively setting idx to 0. Consequently, the out‑of‑bounds write no longer occurs, and the program appears to work.
Using GDB, the author demonstrates that the address of array[9] in fool() is identical to the address of idx in bar() , confirming the stack overlap. The article emphasizes that such "printf‑blessing" merely masks the underlying bug; proper initialization of variables is the correct solution.
Finally, the author notes that while logging statements can sometimes hide bugs, they can also affect program behavior, especially in multithreaded contexts, and should be used judiciously.
IT Services Circle
Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.