Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Educational example to show that sometimes printf as debugging may hide a bug

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 printfs. 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 printfs make a segmentation fault disappear and hence, prove that one must be careful.

like image 725
YuppieNetworking Avatar asked Jun 24 '10 14:06

YuppieNetworking


2 Answers

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 :-)

like image 135
Péter Török Avatar answered Sep 20 '22 15:09

Péter Török


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.

like image 38
AProgrammer Avatar answered Sep 18 '22 15:09

AProgrammer