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};
source share