11

C コード :

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

では、これらのガベージ値は、C のカーテンの後ろにある初期化されていない変数にどのように割り当てられるのでしょうか?

Cが最初に変数「a」にメモリを割り当て、次にそのメモリ位置にあるものはすべて「a」の値になるということですか? または、他の何か?

4

5 に答える 5

17

Cが最初に変数「a」にメモリを割り当て、次にそのメモリ位置にあるものはすべて「a」の値になるということですか?

丁度!

基本的に、C は指示されていないことは何もしません。それが強みでもあり弱みでもあります。

于 2013-03-10T19:38:35.607 に答える
7

Does it mean C first allocates memory to variable 'a' and then what ever there is at that memory location becomes value of 'a'? or something else?

Correct. It is worth mentioning that the "allocation" of automatic variables such as int a is virtually nonexistent, since those variables are stored on the stack or in a CPU register. For variables stored on the stack, "allocation" is performed when the function is called, and boils down to an instruction that moves the stack pointer by a fixed offset calculated at compile time (the combined storage of all local variables used by the function, rounded to proper alignment).

The initial value of variables assigned to CPU registers is the previous contents of the register. Because of this difference (register vs. memory) it sometimes happens that programs that worked correctly when compiled without optimization start breaking when compiled with optimization turned on. The uninitialized variables, previously pointing to the location that happened to be zero-initialized, now contain values from previous uses of the same register.

于 2013-03-10T19:45:40.540 に答える