-1

I'm new to C, so pardon if the question is trivial but could not find an answer on the net. When I do something like:

int main(void)
{
    int numbers[10];

    for(int i = 0; i < 10; i++)
    {
        printf("index: %d; value: %d\n", i, numbers[i]);
    }

    return 0;
}

It prints out random numbers like 0, 1, 1114563524, -1075553756 etc. Why this happens?

Root149
  • 389
  • 1
  • 3
  • 11

3 Answers3

4

This is because in C when you allocate on the stack memory it is not cleared out for you. These numbers you are seeing are the contents of the 4 bytes at the memory address the last time they were set.

If you are looking to get memory that has been cleared and set to a specific value you need to use memset on your stack declared value. (See comment below).

If you would like to do this in one key word, you can use calloc to allocate memory on the heap and clear it in one command. This is where explicit memory management comes into C, so once you calloc, you are also required to call free() upon your memory as well.

dhalik
  • 455
  • 3
  • 11
  • @Root149 This is not correct. It has nothing to do with heap or stack. The values are just not initialized. One can use e.g. `Element element;` and `memset(&element, 0, sizeof(Element))` or `Element *element = malloc(sizeof(Element));` and `memset(element, 0, sizeof(Element))` – Stefan Falk Dec 10 '14 at 08:25
  • See e.g. http://stackoverflow.com/questions/8029584/why-does-malloc-initialize-the-values-to-0-in-gcc – Stefan Falk Dec 10 '14 at 08:28
  • I agree it does not specifically have to do with the heap or stack. But allocating on the heap does give you the ability to use calloc in one key word, whereas allocating on the stack requires using memset also. I will clarify my answer about that. – dhalik Dec 10 '14 at 18:46
0

You have to initialize your array elements if you want to have non-indeterminate values :

int numbers[10] = {0};

An object declared with automatic storage duration without an explicit initializer has an indeterminate value. Accessing an object with an indeterminate value invokes undefined behavior in C.

ouah
  • 142,963
  • 15
  • 272
  • 331
0

For performance reasons, the C language does not implicitly clear memory you get. The only exception are variables of static storage duration (i. e. variables declared static or extern) which receive a value of 0 (or the equivalent zero value) on program start implicitly unless initialized explicitly.

fuz
  • 88,405
  • 25
  • 200
  • 352