Is the following program a valid C program?
#include <stdio.h>
int main()
{
fwrite("x", 1, 1, stderr);
fflush(stderr);
fgetc(stderr);
fwrite("y", 1, 1, stderr);
return 0;
}
Notice that I try to read from stderr.
When I compile it in Visual C++ 2008, and run it, I get the following output:
xy
which makes sense. However, when I redirect stderr to a file (test.exe 2> foo.txt), I get a
“Debug Assertion Failed” window with the message: “Inconsistent Stream Count. Flush between consecutive read and write”. Adding a fflush between the read and write does fix the problem.
(This happens in debug build. In release builds, the second write silently fails).
Is this behavior correct, or is this a compiler library bug? I couldn’t find anywhere any rules describing when reads or writes are illegal in C.
C99 says in 7.19.5.3 (
fopen), paragraph 6:Congratulations for discovering this corner case in practice. The library implementation is completely correct, since you violate the shall quoted above.
And by the way, it is not uncommon to read from
stderr. This is useful whenstdinandstdoutare redirected and no terminal is available. Although C99 doesn’t guarantee it to be readable, I remember some cases on POSIX-like systems where this had actually been done.