I remember when I was in some course of C programming, a teacher once suggested that I use printf
to watch the execution of a program that I was trying to debug. This program had a segmentation fault with a cause that I cannot remember at the moment. I followed his advice and the segmentation fault disappeared. Fortunately, a clever TA told me to debug instead of using printf
s. In this case, it was an useful thing to do.
So, today I wanted to show someone that using printf
could potentially hide a bug but I can't find that old code that had this bizarre bug (feature? hmmm).
Question: Have any of you encountered this behavior as well? How could I reproduce something like this?
Edit:
I see that my question part orients my opinion to "using printf
is wrong". I am not exactly saying that and I don't like taking extreme opinions, so I'm editing a bit the question. I agree that printf
is a good tool, but I just wanted to recreate a case where printf
s make a segmentation fault disappear and hence, prove that one must be careful.
There are cases when adding printf
calls alters the behaviour of the code, but there are also cases when debugging does the same. The most prominent example is debugging multithreaded code, where stopping the execution of a thread may alter the behaviour of the program, thus the bug you are looking for may not happen.
So using printf
statements does have valid reasons. Whether to debug or printf
should be decided on a case by case basis. Note that the two are not exclusive anyway - you can debug code even if it contains printf
calls :-)
You'd have a very hard time to convince me not to use logging (and printf in this situation is an had hoc form of logging) to debug. Obviously to debug a crash, the first things is to get a backtrace and use purify or a similar tool, but if the cause is not obvious logging is by far one of the best tool you can use. A debugger allows you to concentrate on details, logging give you a bigger picture. Both are useful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With