Why does the following C code allow an input stream that is greater than the size of the buffer before it finally results in a segmentation fault? With a character array of size 1 as very_bad
's argument, wouldn't this only allow 1 character of input?
Additionally, what are the implications of initializing c
as an int
and not a char
? Would the statement while ((c = getchar()) != '\n' && c != EOF)
be reading from getchar()
in 4 character increments? Or would the binary representation of the characters be in 4 bytes?
Note: this is text from class, but not HW.
#include <stdio.h>
void very_bad(char* buffer) {
int c; /* NB: int rather than char because the system I/O function
getchar() returns the int value 0xffffffff on end-of-file */
char* dest = buffer;
/* read until newline or end-of-file (Control-Z for the standard input) */
while ((c = getchar()) != '\n' && c != EOF)
*dest++ = c; /* store next character in buffer and move pointer */
printf("%s\n", buffer);
}
int main() {
char buff[1]; /* big trouble waiting to happen */
very_bad(buff);
return 0;
}