Search code examples
clinuxstdio

Confusion about setbuf example of invalid use from man page


From man setbuf on Ubuntu:

You must make sure that the space that buf points to still exists by the time stream is closed, which also happens at program termination. For example, the following is invalid:

Invalid sample code from manpage:

#include <stdio.h>

int main(void)
{
    char buf[BUFSIZ];
    setbuf(stdin, buf);
    printf("Hello, world!\n");
    return 0;
}

Why is it invalid? Local variable buf is destroyed after program returns via return 0;.


Solution

  • Once the return is executed, buf no longer exists, but program execution continues with the calling of exit handlers and closing of streams. So, when the stream is closed, the buffer does not exist.