In a recent interview, I was asked the following question:
You have a bug in your program, after attempting to debug it by inserting statements like printf, console.log, System.out.println, echo, etc, the bug disappears. How can this happen?
I responded with answers like the following:
- You have something with side effects in the print statement, eg:
System.out.println(foo.somethingWithSideEffects())
- Adding printf changes the memory layout of the program, therefore it could cover adjacent memory and prevent crashes
- Undefined Behavior in native code (like uninitialized values, buffer overruns, sequence points, etc)
The interviewer said those aren't the only ways that this could happen, and I couldn't think of any other ways simply adding a printf, etc could "fix" a bug in a program.
What other things could cause this to happen?
The biggest thing that comes to mind is that putting debugging code in can change the timing of the code, which can matter if there is a race condition in the code being debugged. It can be very frustrating to try to debug race conditions that disappear when inspected like this.