You've figured out that printf()
doesn't actually solve the problem in your code, it just masks the problem so you don't get a segmentation fault.
The segmentation fault is a good thing, because it helps you find the error in your code. When you add printf()
, the error is still there but the segmentation fault is gone... so it's harder to find the error.
Memory errors in C programs can result in very strange behavior. Basically, anything can happen if your program has a memory error, and in this particular case what actually happens depends on whether that printf()
call gets executed. It would probably take a bit of sleuthing to figure out exactly what is going on here, but it is possible (for example) that some of your code depends on uninitialized memory, and printf()
leaves behind some values in that memory that cause your other code to proceed harmlessly.
There are a number of different tools you can use to diagnose these problems.
Since your code gets a segmentation fault, you can hook up a debugger and see where the crash is. The incorrect code might crash, or the crash might happen long after the incorrect code has executed.
Valgrind will often tell you which parts of your program rely on uninitialized values, which are a common source of this kind of crash.
Mudflap (compile with gcc -fmudflap
) will also find some of these errors. Mudflap and Valgrind have a lot of overlap, but sometimes one of them will find an error that the other one doesn't.