Why would an automatic variable contain garbage if not set?

In the "third programming language C" and on page 32, I saw the lines that confused me:

Since automatic variables come and go with a function call, they do not store their values ​​from one call to the next and must be explicitly set for each entry. If not installed, they will contain garbage

Does it mean that the following code a

will not contain the garbage when it is finished, and if I declare a

as follows: int a;

then a

will contain garbage?

#include <stdio.h>
int main () {
        int a = 5;
        // int a;
        printf("\n\t %d", a);
}

      

+3


source to share


4 answers


Using the value of an uninitialized variable is undefined. In practice, automatic variables are allocated in processor registers or on the stack. Usually, if they are not initialized, they will receive the value present in the register or memory currently used for the stack. So, for example, a variable int

might contain a piece of memory that was a variable double

in a function called just a minute ago. In other words, the value is random.



+10


source


Consider the following example:

#include <stdio.h>

void fun1(void)
{
    int num1;
    printf("fun1: %i\n", num1);
}

void fun2(void)
{
    int num2 = 7;
    printf("fun2: %i\n", num2);
}

int main(void)
{ 
    fun1();
    fun2();
    fun1();

    return 0;
}

      

On my machine, I get the following output:

fun1: 0
fun2: 7
fun1: 7



As you can see, since it is num1

not initialized, it matters what is on the stack at the time of the call.

You can render the stack in this way at runtime like this:

    main fun1 main fun2 main fun1 main
    [0] SP -> [0] [0] SP -> [7] [7] SP -> [7] [7]
SP -> [x] [x] SP -> [x] [x] SP -> [x] [x] SP -> [x]

Legend: SP = Stack Pointer, x = Don't Care
+2


source


If you don't initialize a variable before using it, it will just fill with whatever the computer had in the memory space where the variable resides, so it's a good idea to always give them an initial value, even if it's zero.

+1


source


  • Automatic variables are allocated on the stack. The stack changes size frequently. Pushing the stack does not overwrite memory, but simply moves the stack pointer. Thus, a function frame (stored registers, local storage and function local variables) is pushed onto the stack instead of another frame and overlaps some information.
  • Static and global variables are placed in the data segment or bss segment. For security reasons, these segments are filled with zeros. Imagine not filling this segment with zeros. Since the computer does not overwrite memory, the new program can access the information of the previous program that was placed in this place.
  • There are also register variables, we ask the compiler to put them in registers. But this is not guaranteed, because the compiler may decide to replace them with automatic variables.
0


source







All Articles