Does C have a template for variables in an array that is assigned the value 0?

I want to know if an array of int elements is declared in C. Is there a pattern according to which only some array values ​​are assigned 0, while others store garbage values? Example:

#include <stdio.h> void main() { int a[5]; int i; for (i=0;i<=4;i++) { printf("%d\n",a[i]); } } 

After compiling and running the program, I get this output, i.e.

 0 0 4195344 0 2107770384 

Thus, zeros exist in a[0], a[1] and a[3] , and a[2] contains the same value at compilation and start, while the value of a[4] continues to change (including negative numbers ) Why does this happen that only some fixed array indices are initialized to zero and do they have something related to the past allocation of memory space?

+4
source share
4 answers

This behavior is undefined and it is just a coincidence. When you declare an array on the stack and do not initialize it, then the array will take values ​​from another (probably previous) stack frame.

In addition:. If you want zero to populate an array declared on the stack (in constant time), you can initialize it using the following initialization syntax:

 int arr[ 5 ] = { 0 }; 

It will write the first element as 0 and zero will fill in the remaining elements. However, if you declared an uninitialized array globally, then it will be automatically filled with zeros.

+8
source

In C, when you declare your array this way, it will not initialize the array. This is all garbage data. Good luck with zeros.

If you want to initialize the array to 0, use

memset(a,0,sizeof(a));

+1
source

This behavior is undefined, and it depends on the OS. The initial value of unassigned arrays is undefined. As a good practice, it is your responsibility to assign meaning to them.

+1
source

I just guess that you ran the code on the terminal to say:

First you run ./a.out or something else that you called.

Secondly, then the termianl process (parent process) calls fork() to create a new process (child process). now the child process just looks the same as the parent process, everything is copied from it by the parent, like all data on the stack.

Thirdly, a child process called exce to load your program. However, the new process did not clear all unused memory, it just saved the value copied from the parent, even the parent process of the part did not initialize, therefore, when you declare int a[5]; in a child process without initialization, it just allocates memory size 20 from the stack, the OS knows that this memory belongs to a[5] , but the value in a[5] is still unknown. It can be any value, it is possible that the depand in the terminal process, maybe not.

So, it is a good practice to initialize variables only when you declare it, if you can.

just use int array = {0};

+1
source

Source: https://habr.com/ru/post/1496235/


All Articles