0

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?

gsamaras
  • 71,951
  • 46
  • 188
  • 305
gmoss
  • 1,019
  • 5
  • 17

2 Answers2

1

Because sometimes it's 0 without being initialized. Simply it is uninitialized which means it can be any value whatsoever, including 0.

It's basically been fluke luck that it has been working as long as it has.

Will Hartung
  • 115,893
  • 19
  • 128
  • 203
  • I see. If it's random with a uniform distribution, getting 0 repeatedly seems incredibly unlikely, so I'm guessing it's not a uniform distribution and probably not truly random. Maybe the next available memory location was already set to 0 somewhere else and then freed up? – gmoss Sep 10 '15 at 00:38
  • 1
    @gmoss It's not technically random. Probably more accurately described as indeterminate. The stack is used continuously during an application's runtime. So accessing an uninitialised stack variable will simply return whatever happens to have been stored there last. And what was "stored there last" is affected by many things such as input to the program which changes the execution path, compiler flags changing the memory layout, adding/removing/change code which changes the memory layout, security features such as ASLR (address space layout randomisation) etc. – kaylum Sep 10 '15 at 00:57
1

You are just (un)lucky.

You can not the value of i for sure, since it's created on the stack. This is undefined behavior. You run the code and i is zero you say, you give me your code (or you run it after 2 days) and i has another value!

As mentioned in this answer:

The value of an uninitialized local variable in C is indeterminate and reading it invokes undefined behavior.

What is Undefined Behavior (UB)? (credits to Alan Au).


Lucky because it worked, unlucky because you didn't spot the mistake!

Community
  • 1
  • 1
gsamaras
  • 71,951
  • 46
  • 188
  • 305