Flushing stdout for accurate logs
What you'll learn: How to ensure your debug messages appear exactly when they happen by forcing the output buffer to empty.
The Mystery of the Missing Log
Have you ever added a printf() right before a crash, but when you ran the program, the message never appeared? You might have assumed the crash happened before the print statement. In C, however, your program might have actually reached the print statement, but the message was "stuck" in transit.
By default, stdout (standard output) is buffered. This means C doesn't send every single character to the screen the moment you call printf(). Instead, it collects characters in a temporary storage area—a buffer—and waits to print them all at once to save system resources.
The Restaurant Kitchen Analogy
Imagine a waiter in a restaurant. If they ran to the kitchen every time a single customer asked for a glass of water, they would be exhausted and inefficient. Instead, they wait until they have three or four requests, then make one trip.
Buffering works the same way. Usually, stdout waits for one of three things:
- The buffer gets full.
- The program sees a newline character (
\n). - The program ends normally.
If your program crashes halfway through, the "waiter" (the buffer) drops the tray. The messages never reach the "kitchen" (your screen), leaving you with misleading information about where the crash occurred.
The Solution: fflush()
To fix this, you can manually force the buffer to empty using fflush(). This is like the waiter deciding that a specific order is so urgent they must run to the kitchen immediately.
#include <stdio.h>
int main() {
printf("Starting a dangerous calculation...");
// Force the text out of the buffer immediately
fflush(stdout);
// Imagine a crash happens here
int *ptr = NULL;
*ptr = 42; // This will cause a Segfault
return 0;
}
Without fflush(stdout), the "Starting..." message might never appear on your terminal because there was no \n to trigger an automatic flush before the crash. With it, you get confirmation that the program reached that specific line.
Key takeaway
Use fflush(stdout); after print statements when debugging crashes to ensure your logs reflect the real-time progress of your code.