I have been looking all over the Internet for an answer to this question (see subject of post). I have been asked this exact question twice. Once at an interview for company and once by a friend and I cannot find the answer for the life of me.
I have actually experienced this error on multiple occasions when debugging without a debugger, and just using print statements to isolate the error. I cannot recall any exact situations, though I am positive I have experienced it. If anyone can provide a link or a reference or point me to something in printf() source that might cause an error to stop occurring when using print statements to debug code I would greatly appreciate the good read.
Thank you,
Matthew Hoggan
I am currently reading the link provided but for further conversation I have posted some of my weak attempts to investigate:
Okay, so i have started to play around myself to try and answer my own question but things are still not 100% clear to me. Below is the output from the g++ compiler using the -S option to output the assembly instead of the executable. The equivalent C++ code is also posted below. My goal is to try and recreate a simple scenario and then try and detect based on the instructions what might be happening at the processor levels. So lets say right after the “call printf” assembly code, which I am assuming is linked from the library files stored in /usr/lib or another lib directory, I tried to access a NULL pointer (not in code), or some other form of operation that would traditionally crash the program. I am assuming that I would have to find out what printf is doing instruction wise to get a deeper look into this?
.file "assembly_test_printf.cpp"
.section .rodata
.LC0:
.string "Hello World"
.text
.globl main
.type main, @function
main:
.LFB0:
.cfi_startproc
.cfi_personality 0x0,__gxx_personality_v0
pushl %ebp
.cfi_def_cfa_offset 8
movl %esp, %ebp
.cfi_offset 5, -8
.cfi_def_cfa_register 5
andl $-16, %esp
subl $32, %esp
movl $0, 28(%esp)
movl $.LC0, (%esp)
call printf
movl 28(%esp), %eax
leave
ret
.cfi_endproc
.LFE0:
.size main, .-main
.ident "GCC: (Ubuntu/Linaro 4.4.4-14ubuntu5) 4.4.5"
.section .note.GNU-stack,"",@progbits
Equivalent C++ code:
#include <stdio.h>
int main ( int argc, char** argv ) {
int x = 0;
printf ("Hello World");
return x;
}
There are several reasons adding a
printf()can change the behavior of a bug. Some of the more common ones might be:For example, an uninitialized local variable might be allocated to a register. Before adding the
printf()the uninitialized variable is used and gets come garbage value that’s in the register (maybe the result of a previous call torand(), so it really is indeterminate). Adding theprintf()causes the register to be used inprintf()andprintf()always happens to leave that register set to0(or whatever). Now your buggy program is still bugy, but with different behavior. And maybe that behavior happens to be benign.