Microsoft Interview Question
Country: -
yes, this could be the case for multithreaded application.
But it also quite often happens for a program when you go beyond the array bounds or similar things. Because inserting 'printf' changes the data layout in your program. Good explanation can be found here:
bytes. com / topic / c / answers/ 498711-segmentation-fault-if-i-dont-use-printf
Seen a similar problem before, as Eugene pointed out might be multi threading issue or might be the addition of printf changes the offsets in the text region such that the crashing instruction which might not actually be an instruction is not picked. I encountered this problem when one of the libraries was built with a different macro while my application had that macro on. But Eugene made a good point, the straight forward is that only.
If this is a multithreaded application, I would think it's a race condition. printf can be a little slow at times, so maybe the printf is changing the relative timing of the threads in a multithreaded application.
- eugene.yarovoi October 16, 2011These types of bugs can be fiendish to track down. I would start by considering the thread that was delayed by the execution of the printf: are there variables that come after the printf, in particular pointers, that are set to a value by a different thread? If so, it's possible that the printf delays its thread enough that other threads are able to do their jobs and initialize variables appropriately, but when the printf is taken away, some of those pointers are dereferenced before other threads can initialize them. A segfault can easily be caused by dereferencing uninitialized pointers.
The best way to stop these bugs is by very careful design of synchronization from the get-go.