So, this has happened to me quite a few times
I write about 100 untested lines of code (I know, bad practice) and then go ahead to test it
As expected, the program crashes
Spend hours debugging, to no avail
And then I add a print statement to check where the code stopped, and hey presto! The code completes execution
I remove the print statement, the code gets stuck

Also, the codes don't use any low level functions that might be interfered by print statements anyhow

Till today, never understood how a print statement helps codes execute properly

  • 0
    Where does it get stuck? Does this runtime support thread dumps and such?
  • 0
    With C/C++, if your code crashes, it's because it included undefined behaviour, and then anything can happen. You can't even rely on printf debugging because the UB doesn't start from the line with the UB, but applies to the whole program.
  • 1
    Use a debugger
  • 0
    @Fast-Nop I couldn't understand the part about printf debugging not being useful.
    Can you please elaborate?
  • 0
    @asgs One of the incidences was with Java. It was supposed to call a function from an external library but it wasn't (or the function wasn't returning, idk.... The println after that line didn't work)
    I added a println before that line for debugging and the println after the call also executed
    I commented the println before the call and it again stopped working

    This was way back before I understood OS. Could it be somehow related to flushing my buffers? Like does println flush buffers or something?
  • 1
    @rutvora the compiler may reorder things in your code as long as it doesn't change in the abstract C machine under the assumption that there is no undefined behaviour.

    Say you have some line where a division by 0 occurs, and you do printf("got here"), then the compiler may change the order because the division and the printf are independent.

    So even if the printf is BEFORE the division, the division may still crash your program before the printf is executed, leading to the wrong conclusion that the crashing line must be before the printf while it is actually after the printf in source code.

    At the very least, you'll need compiler barriers around the printf to prevent this from happening. Actually even memory barriers if you run the resulting executable on a CPU with out of order execution.
Add Comment