The type of '1'
is int
in C, not char
, so you are reading SIZE*sizeof(int)
bytes in each fread
. If sizeof(int)
is greater than 1 (on most modern computers it is), then you are reading past the storage for buffer
. This is one of the places where C and C++ are different: in C, character literals are of type int
, in C++, they are of type char
.
So, you need chars_read = fread(buffer, 1, SIZE, stdin);
because sizeof(char)
is 1 by definition.
In fact, I would write your loop as:
while ((chars_read = fread(buffer, 1, sizeof buffer - 1)) > 0) {
buffer[chars_read] = 0; /* In case chars_read != sizeof buffer - 1.
You may want to do other things in this case,
such as check for errors using ferror. */
printf("%d, %s\n", chars_read, buffer);
}
To answer your another question, '\0'
is the int
0, so {'\0'}
and {0}
are equivalent.
For setvbuf
, my documentation says:
The
size
argument may be given as zero to obtain deferred optimal-size buffer allocation as usual.
Why are you commenting with \\
instead of //
or /* */
? :-)
Edit: Based upon your edit of the question, sizeof("1")
is wrong, sizeof(char)
is correct.
sizeof("1")
is 2, because "1"
is a char
array containing two elements: '1'
and 0
.