Skip to content

December 3, 2009

3

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!

3 Comments Post a comment
  1. Valentin
    Dec 4 2009

    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. :D

  2. Dec 4 2009

    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.

  3. Valentin
    Dec 4 2009

    Yes, share the power of printf and fflush!

Share your thoughts, post a comment.

(required)
(required)

Note: HTML is allowed. Your email address will never be published.

Subscribe to comments

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word