Debugging C with print statements
This is the most basic tip I can give all students that have to start working in C. Use: fflush(stdout);
If your program crashes, the output stream just gets dumped instead of well.. outputted. So then, even if you use printf statements to figure out where your program crashed, the last print statement you see might not be the last one that was executed. BUT, if you put fflush(stdout) after your debug prints, then they will be immediately shown, so you know what’s going on. That simple!



Aah, I should tell you about my debug(…) define!
If you’re debugging a multi-threaded program you can’t just output to stdout as everything comes out mangled. I had to create a define that opened a file for writing for each thread and passed all define parameters to fprintf with __VA_ARGS__. This way, I used debug just like printf, only everything was outputted to a file corresponding to the thread number.
You can also use the same trick to put a timestamp on every outputted message and if you want to remove all debug messages from showing on screen, all you have to do is redefine debug(…) to nothing.
Yeah, I do something similar with “debug()”, but the idea for threads is cool, I didn’t think of that.
This post is more for people having their first C assignments rather than older coders
I have repeated the above statements many many times and I figured it might help some people if I blog it.
Yes, share the power of printf and fflush!