C编程寄存器值?

时间:2015-02-16 17:16:01

标签: c assembly cpu-registers

在下面的程序中,第二个printf语句打印与第一个printf语句相同的mem位置和值。为什么?

是否因为调用第二个printf语句时寄存器的值没有改变? y变量从未初始化,因此当调用printf时,它只会找到' x'在堆栈上?

#include <stdio.h>
#include <stdlib.h>

void foo1( int xval ) {

    int x;
    x = xval;

    /* print the address and value of x here */
    printf("x\t | %#x\t\t| %d\n", &x, x);
}

void foo2( int dummy ) {

    int y;

    /* print the address and value of y here */
    printf("y\t | %#x\t\t| %d\n", &y, y);
}


int main() {

    printf("Variable | Memory Location\t| Value\n");
    foo1(7);
    foo2(11);

    return( 0 );
}

输出:

Variable | Memory Location  | Value
x    | 0xe6ffa3cc       | 7
y    | 0xe6ffa3cc       | 7

1 个答案:

答案 0 :(得分:0)

foo1()内,你需要分配值x,它位于地址0xe6ffa3cc下的堆栈上。这意味着使用值7初始化此特定内存区域。

foo2内,您要打印未初始化的值y。这个值也位于堆栈上,我敢打赌它与x之前的地址意外相同(你正在调用具有相同签名的函数,这可能会导致相同的堆栈&#34;布局& #34)。由于y未初始化,因此它包含&#34;垃圾&#34;来自之前的电话,即7。

此行为未定义。在不同的平台(操作系统,硬件)上,它可能会给你不同的结果。