【问题标题】:True memory locations of C variablesC 变量的真实内存位置
【发布时间】:2017-06-06 15:18:25
【问题描述】:

为了了解更多关于 C 的知识,过去 2 天我一直在玩它。我想开始研究 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", &amp;a);Please enter number one:456789AB

标签: c gdb hexdump


【解决方案1】:

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

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

09010000 => 00000109 => 265 十进制

【讨论】:

  • 是的...我应该知道的。现在我觉得很笨。非常感谢!
猜你喜欢
  • 2015-11-09
  • 2018-12-06
  • 1970-01-01
  • 2015-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多