Reputation: 89
I want to know if an array of int elements is declared in C. Is there a pattern according to which only some values of the array are assigned to 0 while others store garbage values? Ex:
#include <stdio.h>
void main()
{
int a[5];
int i;
for (i=0;i<=4;i++)
{
printf("%d\n",a[i]);
}
}
After I compile and run the program I get this output,i.e.
0
0
4195344
0
2107770384
So zeroes are there in a[0], a[1]
and a[3]
while a[2]
contains the same value each time compiled and run whereas a[4]
value keeps on changing (including negative numbers). Why does this happen that only some fixed indices of an array are initialized to zero and does it have something related to past allocation of memory space?
Upvotes: 4
Views: 294
Reputation: 2857
I just guess you run the code by terminal to say:
First, you run ./a.out
or something else you named.
Second, then the termianl process (the parent process) call fork()
to create a new process (the child process). now the child process is just looks the same as the parent process, everything is copyed from it's parent, like all data in stack memory.
Third, the child process called exce
function to load you program.However, the new process didn't clear all not used memory, it just keep the value copyed from parent, even the part parent process did't initialize. So when you declare int a[5];
in child process without initialized, it just alloc a memeory sizeof 20 from stack ,OS know those memory belong to a[5]
, but the value in a[5]
, still the unknown. It can be every value, maybe that depand on the terminal process , maybe not.
So, It's a good custom to initialize the variables just when you declare it if you can.
just use int array = {0};
Upvotes: 1
Reputation: 3751
This behaviour is undefined and it is merely a coincidence. When you declare an array on the stack and do not initialize it then the array will take on values from another (likely the previous) stack frame.
Aside: If you wanted to zero-fill an array declared on the stack (in constant time) then you can initialize it using the following initialization syntax:
int arr[ 5 ] = { 0 };
It will write the first element as 0 and zero-fill the rest of the elements. However, if you declared an uninitialized array globally then it will automatically be zero-filled.
Upvotes: 8
Reputation: 172448
This is an undefined behavior and it depends on the OS. The initial value of unassigned arrays is undefined. As a matter of good practice it is your responsibilty to assign them a value.
Upvotes: 1
Reputation: 1277
In C, when you declare your array that way it will not initialize the array. That's all garbage data. It's luck that there are zeros.
If you want to init the array to 0 use
memset(a,0,sizeof(a));
Upvotes: 1