After having been busy a couple months, I'm going back through K&R to get back in the habit of typing C, and to get used to the conventions/syntax, etc... so I can pick up where I left off again...
Anyway, I found a weird set of behavior in one program I typed out from the book.
I haven't modified it at all(well, I added a \n in the output to make it more sane), but other than that the code is exactly as it appeared in the book, minus comments.
Code:
#include <stdio.h>
#define MAXLINE 100
int getline(char [], int);
void copy(char [], char []);
int main(void)
{
int len, max;
char line[MAXLINE];
char longest[MAXLINE];
max = 0;
while((len = getline(line, MAXLINE)) > 0)
if(len > max) {
max = len;
copy(longest, line);
}
if(max)
printf("\n%s\n", longest);
return 0;
}
int getline(char s[], int lim)
{
int c, i;
for(i = 0; i< lim-1 && (c = getchar()) != EOF && c != '\n'; i++)
s[i] = c;
if(c == '\n') {
s[i] = '\0';
++i;
}
return i;
}
void copy(char to[], char from[])
{
int i;
i = 0;
while((to[i] = from[i]) != '\0')
++i;
}
Now, normally this code behaves exactly as I expect it to. However, there is one exception:
If I type the program name and then press Ctrl+D, the program exits immediately, as expected.
If I type any text, then press Enter, then Ctrl+D, it prints the longest line, then exits.
However, if I type any amount of text, including any number of carriage returns, but _don't_ press Enter at the end, and then press Ctrl+D, nothing happens. If I press Ctrl+D another 2 times(total of 3 presses), this happens:
Code:
$ ./ex1-16
abc #I'm pressing abc^D^D^D; the first two appear to do nothing.
abc@ô@ÿwÐôÿ¿Ðd@/
What I want to know is, how does that garbage get into the array? In other words, what's actually going on underneath the code?