Search code examples
carraysvariablesuninitialized-constant

Uninitialized variable or array in C


Where do the results of an uninitialized array in C come from? Are they randomly assigned values or it's just previous values that are stored in the memory?

#include <stdio.h>

int main (void)
{
    int values[10];
    int index; 

    values[0] = 197;
    values[2] = -100;
    values[5] = 350;
    values[3] = values[0] + values[5];
    values[9] = values[5] / 10;
    --values[2];

    for ( index = 0; index < 10; index++ )
        printf ("values[%i] = %i\n", index, values[index]);

    return 0; 
}

and the output:

$ ./a.exe
values[0] = 197
values[1] = 0
values[2] = -101
values[3] = 547
values[4] = 8
values[5] = 350
values[6] = 51
values[7] = 0
values[8] = 44045216
values[9] = 35

Solution

  • Chapter and verse:

    6.2.4 Storage durations of objects
    ...
    5 An object whose identifier is declared with no linkage and without the storage-class specifier static has automatic storage duration, as do some compound literals. The result of attempting to indirectly access an object with automatic storage duration from a thread other than the one with which the object is associated is implementation-defined.

    6 For such an object that does not have a variable length array type, its lifetime extends from entry into the block with which it is associated until execution of that block ends in any way. (Entering an enclosed block or calling a function suspends, but does not end, execution of the current block.) If the block is entered recursively, a new instance of the object is created each time. The initial value of the object is indeterminate. If an initialization is specified for the object, it is performed each time the declaration or compound literal is reached in the execution of the block; otherwise, the value becomes indeterminate each time the declaration is reached.

    Emphasis added.

    Basically, objects with auto storage duration are not implicitly initialized to any particular value - they have the value of whatever was last written to that particular memory location1. You cannot rely on that value being 0 (or anything else).

    That last sentence in the quote above applies to situations like this:

    for (;;)
    {
      int x;
      do_something_with( x );
    }
    

    Each iteration of the loop effectively destroys and re-creates x, and you cannot rely on value written to x in any iteration of the loop to be carried over to the next iteration. In practice on x86-like systems it most likely will be carried over, but don't assume that's the case everywhere.

    Note that an implementation may decide to initialize auto variable with some known value when building in debug mode or something.


    1. The mechanics of which are wide and varied and not worth going into here.