C Miscellany


Using fflush() to force output

Consider the following C program: (source file)
#include <stdio.h>

int main ()
{
    int A[10];
    int *B;
    int i;

    for (i=0; i<10; i++) {
        A[i] = 1;
    }

    for (i=0; i>10; i++) {
        B[i] = A[i];
    }

}
  
The program has an error. Upon compilation (with, say, gcc) we get:
% gcc -o example example.c
% example
Segmentation fault (core dumped)
   
To catch the error, let's try adding print statements: (source file)
int main ()
{
    int A[10];
    int *B;
    int i;

    printf ("Before first for-loop\n");

    for (i=0; i<10; i++) {
        A[i] = 1;
    }

    printf ("After first for-loop\n");

    for (i=0; i<10; i++) {
        B[i] = A[i];
    }

    printf ("After second for-loop\n");

}
   
Upon execution, it is quite possible that you won't see anything printed, or will see only a part of the output: This makes it difficult to pinpoint the source of the error.

To force output to be written immediately, use fflush(): (source file)

int main ()
{
    int A[10];
    int *B;
    int i;

    printf ("Before first for-loop\n");
    fflush (stdout);

    for (i=0; i<10; i++) {
        A[i] = 1;
    }

    printf ("After first for-loop\n");
    fflush (stdout);

    for (i=0; i<10; i++) {
        B[i] = A[i];
    }

    printf ("After second for-loop\n");
    fflush (stdout);
}
   
Upon compilation and execution, we see the following output:
% gcc -o flush flush.c
% flush
Before first for-loop
After first for-loop
Segmentation fault (core dumped)
   
Now we know the seg-fault occurs in the second loop.

Exercise 1: What is the error above? Show how you would use a debugger to find the error. What fflush() does:

Exercise 2: If stdout can be treated like a file, can one use this in fprintf()? Find out what happens with the following code:

    printf ("Hello ");
    fprintf (stdout, "World!\n");
   



© 2003, Rahul Simha (revised 2017)