m2oTech.com

  • Increase font size
  • Default font size
  • Decrease font size

Don't forget \n

Print PDF

Ever used a simple printf statement to debug a C program without a proper debugger? If so you may have noticed some strange behavior if you forgot to include a carriage return (\n) in that statement.

While debugging a Segmentation fault I pasted following statement in a few places in the program, to see where the violation occurred:

printf("kkkkk");

To my surprise I saw no "kkkkk" not either one, even though I made sure I included one of it as control all the way up the program. It turns out I needed to modify that line into

printf("\nkkkkk");

that is, adding a "\n".

The reason for this is that C does not flush to stdout (i.e. does not display printf and other messages) until a carriage return is encountered. By not adding it in the statement we incurred in the Segmentation fault and the program terminated before messages could print out.

Of course there are ways to force flushing without adding a newline.

 

Add your comment

Your name:
Subject:
Comment:
  The word for verification. Lowercase letters only with no spaces.
Word verification: