C变量的真实内存位置

7
为了更好地学习C语言,我过去两天一直在玩它。我想开始研究C语言在运行时的结构,因此我编写了一个糟糕的程序,要求用户输入两个整数值,然后打印整数变量的内存位置。然后,我想验证数据是否确实存在,因此我使用getchar()暂停程序,以便打开GDB并挖掘内存段以验证数据,但是那些位置上的数据对我来说没有太多意义。请问有人可以解释这里发生了什么吗?

程序代码:

#include <stdio.h>

void pause();

int main() {
   int a, b;
   printf("Please enter number one:");
   scanf("%d", &a);
   printf("Please enter number two:");
   scanf("%d", &b);
   printf("number one is %d, number two is %d\n", a, b);
  // find the memory location of vairables:
   printf("Address of 'a' %pn\n", &a);
   printf("Address of 'b' %pn\n", &b);
   pause();
}

void pause() {
   printf("Please hit enter to continue...\n");
   getchar();
   getchar();
}

输出:

[josh@TestBox c_code]$ ./memory 
Please enter number one:265
Please enter number two:875
number one is 265, number two is 875
Address of 'a' 0x7fff9851314cn
Address of 'b' 0x7fff98513148n
Please hit enter to continue...

内存段的GDB十六进制转储:

(gdb) dump memory ~/dump2.hex 0x7fff98513148 0x7fff98513150

[josh@TestBox ~]$ xxd dump2.hex 
0000000: 6b03 0000 0901 0000                      k.......

提示:如果使用GDB以十六进制查看数据,最好将数据输入为十六进制。scanf("%X", &a);请输入数字一:456789AB - chux - Reinstate Monica
1个回答

9
6b03000009010000是小端(最低有效字节在前)的。为了更自然地读取它们,请颠倒字节的顺序:

6b030000 => 0000036b => 十进制中的875

09010000 => 00000109 => 十进制中的265


是啊...我应该知道的。现在感觉很蠢。非常感谢! - Joshua Faust

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接