Mysterious c debugging problem when trying to utilize printfs
Ok, folks. I've never encountered this before and it boggles the mind and is illogical. I have a somewhat complex loop and I want to try and see if everything is working by putting some printf statements. I look the intermed开发者_如何学运维iate products using printf and verify that the answer is ok. Then, when I comment out the printf to the intermediate products, the answer is WRONG. Has anyone ever encountered this? This is driving me insane and I don't see how the printfs could change an answer.... X_x If it helps, I am using a c/c++ compiler for a DSP. Thanks for any advice..
Here is a snippet...
printf("splitBackground = %d, numWindowPoints = %d\n", splitBackground, numWindowPoints);
splitBackground = splitBackground/numWindowPoints;
printf("%d ", splitBackground);
This is good but when I comment out the first line of code, it turns out to be hugely incorrect. :(
Most likely you've made a mistake in your code that results in undefined behavior. And "undefined" implies "it might work under some circumstances".
Why would inserting a printf
make it work? Some possibilities:
It changes the timing relationships between different parts of your program, or between your program and the rest of the world.
The printf call inhibits a compiler optimization that might otherwise take place.
The printf call changes the internal state of the standard library in a way that prevents the bug from occurring.
The printf call interacts with the hardware in a way that prevents the bug from occurring.
(Note that many of the same considerations are also true when running under a debugger -- thus the term "heisenbug": a bug that only occurs when you're not watching for it.)
Personally I would print to stderr, not stdout.
If you're using an IDE I would take full advantage of the debugger to try to resolve your issues. Like in Visual Studio 2010, Eclipse or Netbeans, add break points and slowly step through the lines of code.
your printf's can have side-effects (modify some data leading to correct results). in any case it would be very helpful to look at simplified example of the problematic code
Probably, this is stack corruption, and your printf
s somehow extend the stack or trigger a guard page or something. But it's hard to say anything without the rest of the code.
精彩评论