How garbage values ​​are assigned to variables in c

C code:

int a; printf("\n\t %d",a); // It'll print some garbage value; 

So, how are these garbage values ​​assigned to uninitialized variables behind the curtains in C?

Does this mean that C first allocates the memory of the variable 'a', and then what has ever been in this memory cell becomes the value of 'a'? or something else?

+7
source share
4 answers

Does this mean that C first allocates memory for the variable 'a', and then what has ever been in this memory cell becomes the value of 'a'?

Right!

Basically, C does nothing that you are not talking about. This is both his strength and her weakness.

+9
source

Does this mean that C first allocates the memory of the variable 'a' and then that the value "a" ever becomes in that memory location? or something else?

Correctly. It is worth noting that the "distribution" of automatic variables, such as int a , practically does not exist, since these variables are stored on the stack or in the CPU register. For variables stored on the stack, "distribution" is performed when the function is called and reduced to an instruction that moves the stack pointer to a fixed offset calculated at compile time (combined storage of all local variables used by this function, rounded to the correct alignment).

The initial value of the variables assigned to the CPU registers is the previous contents of the register. Because of this difference (case versus memory), it sometimes happens that programs that work correctly when compiling without optimization begin to break when compiling with optimization. Uninitialized variables that previously indicated a place that turned out to be zero initialized now contain values ​​from previous uses of the same register.

+6
source

int a ;

When declaring a variable, memory is allocated. But this variable is not assigned, which means that the variable a not initialized. If this variable a declared, but is no longer used in the program, it is called the garbage value . For example:

 int a, b; b=10; printf("%d",b); return 0; 

Here it is declared, but no longer assigned or initialized. Thus, this is called the garbage value .

+1
source

Initially, the memory has some values, these are unknown values, also called garbage values, when we declare a variable, some memory was reserved for the variable according to the data type that we specified when declaring, so the initial memory value is an unknown value if we initialize which something else meaning, then our meaning will be in this place of memory.

0
source

All Articles