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.
In that example,
stdoutwill be flushed aftermainhas returned.When that happens,
bufis out of scope, you can’t legally use it anymore. So the program will exhibit undefined behavior.bufneeds to live as long asstdoutis open, andstdoutoften stays open until aftermainhas returned. So you should use a global, static or heap-allocated buffer.