3

By running this code

char array[6];
int i;
for ( i = 0; i < 6; ++i )
    printf("%i ", array[i]);

Possible output:

64 0 -64 77 67 0

I get always the last element 0, although I was expecting random value. It is compiler dependent? I'm using gcc.

10
  • 5
    You don't get random numbers, but you get indeterminate numbers. Commented Oct 19, 2016 at 13:59
  • 2
    The simple answer - No Commented Oct 19, 2016 at 14:00
  • 1
    Curious - always the last element 0. How many times is always ? Commented Oct 19, 2016 at 14:07
  • 3
    Due to the automatic storage of your array, probably, the code before the function where the code is placed, leave that 0 into the stack. Commented Oct 19, 2016 at 14:12
  • 2
    @Tom don't waste anymore time on this, or step through the assymbly code with a debugger if you want to know what exactly happens in your case. Commented Oct 19, 2016 at 14:21

3 Answers 3

4

No. There's no such thing guaranteed by the C standard for local variables.

The values of the uninitialized array has indeterminate values. So, you can't access them and since you do, your code has undefined behaviour.

But the variables with static storage duration such as global variables, static qualified variables etc are initialized with zero.

Sign up to request clarification or add additional context in comments.

2 Comments

Hmmm. ...So, you can't access them.... Should that be ...you should not access them...?
Strictly speaking you must not access them is the most accurate ;-)
3

The contents of a variable (and by extension, the elements of an array) that do not have static storage duration (globals, static locals) are undefined.

The fact that the last element in the array happens to be 0 essentially is random.

Comments

3

Last element is zero in string constants like "Test" or char array[] = "Test";. In your example last value is zero by chance.

Try this:

void f1() // prepare non-zero stack
{
  char array[40];

  memset( array, 32, sizeof array ); 
}

void f2() // your array
{
  char array[6];
  int i;
  for ( i = 0; i < 6; ++i )
    printf("%i ", array[i]);
}

int main()
{
  f1();
  f2();
  return 0;
}

5 Comments

OP includes statement: I get always the last element 0. If this is an accurate observation (as opposed to an exaggeration) then by chance may not be accurate.
@ryyker It is by chance. I can show example how to get value other than 0. (Has to fill the stack before calling such function.) And the question is "Does C always initialize...", not "is this in my case".
@i486 I would be grateful to see this example, can you show it please?
@Tom Try example in the answer above.
@i486 You have right, now I don't get 0 anymore, Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.