I'm teaching myself C, and programming in general, and really enjoying it, so here's a beginner question.
I had used the function readLine() to get user input of undefined length throughout a program. Here is the function:
char *readLine(void){
int len=128;
unsigned int i;
int c=EOF;
char *input = malloc(len*sizeof(char));
while((c=getchar())!='\n' && c!=EOF){
input[i++]=(char)c;
if (i==len){
input=realloc(input, sizeof(char)*(len+i));
len+=i;
}
}
input[i]='\0';
input=realloc(input,sizeof(char)*(i+1));
return input;
}
Notice that I never initialized i. Whoops. Except, until today, it worked just fine. For example, the following code worked perfectly to get user input:
printf("Enter the hex-encoded cipher: \n");
cipher = readLine();
and still works if I leave i uninitialized: the debugger tells me that i is set to 0 by default. With the next piece of code I wrote, it stopped working, and after about ten seconds in the debugger I banged my head on the table.
Question: Why did it work? Why is i sometimes already 0 without being initialized?