0

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
el-aasi
  • 307
  • 2
  • 18
  • 4
    Yes, it is normal *undefined behavior*. – Ian Abbott Apr 05 '18 at 16:34
  • 3
    They are not initialised and have some value by chance. What is unclear about that? – Yunnosch Apr 05 '18 at 16:34
  • `int values[10];` is an _automatic variable_, allocated on the stack. Automatic variables are not initialized to zero be default; you'll have to do that yourself. – Paul Ogilvie Apr 05 '18 at 16:35
  • thanks for responses @Yunnosch , sorry if my question offended you, as I said I am new to see and in general to computers (meaning more than average usage) I understand that the reason C requires to specify the number of variables when defining an array so it can allocate it in the memory, but I did not know that if you do not initialize a variable it will display anything but zero, that is basically the reason why I asked.....so yeah the overall answer to your question it is unclear why it behaves like that and thanks to others and you I now understood.... – el-aasi Apr 05 '18 at 16:54
  • @Yunnosch , thanks for the suggested link, I did not know about it, and yeah thanks again for the reply, cheers – el-aasi Apr 05 '18 at 17:59
  • 1
    C is designed for speed. Automatically initializing variables to zero would take time. If you need to initialize some, you can. If you don't need them initialized, the compiler won't waste the time. – Lee Daniel Crocker Apr 05 '18 at 18:10

4 Answers4

2

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.

John Bode
  • 119,563
  • 19
  • 122
  • 198
  • thanks for the reply, it explains a lot, what is the book that you quoted from? – el-aasi Apr 06 '18 at 10:23
  • @el-aasi: [Online C 2011 Standard](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf) (PDF file). It's not the *official* standard (that costs money), but it's good enough for most circumstances. – John Bode Apr 06 '18 at 14:03
1

What do you think "uninitialized" means?

It means the value has not been set. Because it has not been set, it could have any value stored there.

Maybe 0, maybe 547...
Any value is valid, and there are no guarantees what you will find.

abelenky
  • 63,815
  • 23
  • 109
  • 159
1

Uninitialized values are just memory addresses that have not yet been written to by your application. It would be like having a notepad that is used by everyone around you. When your program runs, it's given a small section of that notepad that may or may not have been used by someone else before. If it was (most likely), then it will still have something written on it, but probably will not make any sense to you. If you want to know what's there, you must write something. In general, we will write 0's to it which is like erasing everything to start with empty paper.

Ben
  • 298
  • 1
  • 8
0

Well this is C programming 101. C is a procedure-oriented language and does not implement some features present in Object Oriented languages (such a Java) such as "automatic" and guaranteed initialization of variables.

If you declare an auto variable (on stack not dynamically allocated) in C and do not provide an initial value, then this variable will have what we call a "garbage value". This is the general behavior but specific implementations can vary.

Let me give an example:

int a;  //a variable with no initial value
printf("%d", a); 

We can't predict what this will print. May be 0 or may be anything else. The program can crash too. Essentially, this is undefined behavior.

If the same was done in Java, then that would surely print 0 (because Java initializes all integers to 0 by default).

Now coming to your array question: It does not matter whether this is a single integer or an array of integers. Any memory location to which you don't assign a value explicitly will have a "garbage value". It can be 0 or something else. This behavior is completely machine dependent and unpredictable.

Bottom line is: ensure that variables are initialized before use.

paratrooper
  • 434
  • 1
  • 10
  • 18
  • thanks for the reply, it cleared a lot, have no idea who and why voted -1....unfortunately I am a newbie on StackOverflow and my ratings are not displayed ) – el-aasi Apr 05 '18 at 17:04
  • never mind the negative voting. Glad i could help :) – paratrooper Apr 05 '18 at 17:08
  • I am not sure if it is me, and the fact that I am a newbie in here and in computer science at all and ask a lot of stupid questions that most probably already has been asked before but I just can't find them, but sometimes the community is slightly passive aggressive.... not all of course but, some.... – el-aasi Apr 05 '18 at 17:11
  • 1
    `printf("%d", a);` is not a "we can't predict what this will print" issue - it is worse. Attempting to read an uninitialized `int` is _undefined behavior_. Code may crash without printing anything, print `0` or the usual "who-knows-what" behavior. "Any memory location to which you don't assign a value explicitly will have a "garbage value". It can be 0 or something else." misleads as it does not clearly assert that the reading attempt itself is undefined, not just the value. – chux - Reinstate Monica Apr 05 '18 at 18:15
  • 1
    Implicit initialization or not of variables is not a distinguishing factor between procedural and OO languages; there are circumstances in which C guarantees the value of uninitialized objects. – mlp Apr 05 '18 at 23:07
  • I agree that is not a distinguishing factor between C and OO languages. I just gave one specific example. And I agree indeed in cases like calloc, C zeroes the blocks. I have updated my statement to say local variables allocated on stack. Also what I really meant was "guaranteed initialization" of variables which OO languages provide. Updated my statements to reflect that. – paratrooper Apr 06 '18 at 02:08