C变量的真实内存位置

时间:2017-06-06 15:18:26

标签: c gdb hexdump

为了更多地了解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.......

1 个答案:

答案 0 :(得分:9)

6b03000009010000是little-endian(最低有效字节优先)。要以更自然的方式阅读它们,请颠倒字节的顺序:

6b030000 =&gt; 0000036b =&gt;十进制875

09010000 =&gt; 00000109 =&gt;十进制265