问题
In 'The C programming language' third edition and on p.32 I saw those lines which make me confused:
Because automatic variables come and go with function invocation, they do not retain their values from one call to the next, and must be explicitly set upon each entry. If they are not set, they will contain garbage
Is it saying that for the following code, a
will not contain garbage after the program finished its execution and if I declare a
like this: int a;
then a
will contain garbage?
#include <stdio.h>
int main () {
int a = 5;
// int a;
printf("\n\t %d", a);
}
回答1:
Using the value of a not initialised variable is undefined behaviour. In practice automatic variables are allocated in processor registers or on the stack. Normally if not initialised they will get the value present in the register or memory used for the stack at the moment. So e.g. an int
variable may contain a part of memory which was double
variable in a function called just a moment ago. In other words the value is random.
回答2:
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, because num1
is not initialized, it has the value of whatever is on the stack at the time of the call.
You can visualize the stack like this during program execution 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
回答3:
If you don't initialize the variable before using it it will just get filled with whatever the computer had in the memory space where the variable is located, that's why it is good practice to always give them an initial value, even if it is zero.
回答4:
- Auto variables are allocated on stack. Stack change it's size very often. Pushing on stack does not overwrite memory, but just move stack pointer. So, function frame (saved registers, local storage and local variables of function) is placed on stack instead of other frame and overlap some information.
- Static and global variables are placed in data segment or bss segment. This segments are filled with zeros due to security reasons. Imagine, that you didn't fill this segment with zeros. As computer doesn't overwrite memory new program can get access to information of previous program that was allocated on this place.
- There are also register variables, we ask compiler to place them in registers. But it is not guaranteed, because compiler may decide to substitute them with auto variables.
来源:https://stackoverflow.com/questions/25430277/why-automatic-variable-will-contain-garbage-if-it-is-not-set