Search code examples
clinuxbuffersystems-programming

why is a buffer local to main( ), and then fail to explicitly close the streams a bug?


I was learning linux system programming, O'reilly. It says "A common mistake is to declare the buffer as an automatic variable in a scope that ends before the stream is closed. Particularly, be careful not to provide a buffer local to main(),and then fail to explicitly close the stream."

then it shows a buggy code example:

#include <stdio.h>
int main()
{
    char buf[BUFSIZ];

    /*set stdin to block-buffered with a BUFSIZ buffer*/
    setvbuf(stdout,buf,_IOFBF,BUFSIZ);
    printf("Arr!\n");
    return 0;

}

I compile and execute the code .. and don't really understand what this kind of code will cause ... please help me understand this concept, thank you all.


Solution

  • In that example, stdout will be flushed after main has returned.

    When that happens, buf is out of scope, you can't legally use it anymore. So the program will exhibit undefined behavior.

    buf needs to live as long as stdout is open, and stdout often stays open until after main has returned. So you should use a global, static or heap-allocated buffer.