1

这是一个简单的 C 程序:

#include <stdio.h>
int main(int argc, char* argv[] ){
    int x = 10;
    int* ptr = &x;
    ptr++;
    printf("%x   %d \n",  ptr,  *ptr);
}

在 Ubuntu 64 位上使用 GNU 调试器,我从 main 函数的开始逐步调试程序,这是调试器的结果:

Temporary breakpoint 1, main (argc=1, argv=0x7fffffffe0f8) at sigseg4.c:28
28  int main(int argc, char* argv[] ){
(gdb) display /a $sp
1: /a $sp = 0x7fffffffdfe0
(gdb) display /a $bp
2: /a $bp = 0xffffffffffffe010
(gdb) display /a &x
3: /a &x = 0x7fffffffdffc
(gdb) display /d x
4: /d x = 21845
(gdb) display /a &ptr
5: /a &ptr = 0x7fffffffe000
(gdb) display /a ptr
6: /a ptr = 0x7fffffffe0f0
(gdb) display /d *ptr
7: /d *ptr = 1
(gdb) next
29      int x = 10;
1: /a $sp = 0x7fffffffdfe0
2: /a $bp = 0xffffffffffffe010
3: /a &x = 0x7fffffffdffc
4: /d x = 21845
5: /a &ptr = 0x7fffffffe000
6: /a ptr = 0x7fffffffe0f0
7: /d *ptr = 1
(gdb) next
30      int* ptr = &x;
1: /a $sp = 0x7fffffffdfe0
2: /a $bp = 0xffffffffffffe010
3: /a &x = 0x7fffffffdffc
4: /d x = 10
5: /a &ptr = 0x7fffffffe000
6: /a ptr = 0x7fffffffe0f0
7: /d *ptr = 1
(gdb) next
31      ptr++;
1: /a $sp = 0x7fffffffdfe0
2: /a $bp = 0xffffffffffffe010
3: /a &x = 0x7fffffffdffc
4: /d x = 10
5: /a &ptr = 0x7fffffffe000
6: /a ptr = 0x7fffffffdffc
7: /d *ptr = 10
(gdb) 
32      printf("%x   %d \n",  ptr,  *ptr);
1: /a $sp = 0x7fffffffdfe0
2: /a $bp = 0xffffffffffffe010
3: /a &x = 0x7fffffffdffc
4: /d x = 10
5: /a &ptr = 0x7fffffffe000
6: /a ptr = 0x7fffffffe000
7: /d *ptr = -8192
(gdb) next
ffffe000   -8192 
33  }
1: /a $sp = 0x7fffffffdfe0
2: /a $bp = 0xffffffffffffe010
3: /a &x = 0x7fffffffdffc
4: /d x = 10
5: /a &ptr = 0x7fffffffe000
6: /a ptr = 0x7fffffffe000
7: /d *ptr = -8192
(gdb) next
__libc_start_main (main=0x5555555546aa <main>, argc=1, argv=0x7fffffffe0f8, 
    init=<optimized out>, fini=<optimized out>, rtld_fini=<optimized out>, 
    stack_end=0x7fffffffe0e8) at ../csu/libc-start.c:344
344 ../csu/libc-start.c: No such file or directory.
1: /a $sp = 0x7fffffffe020
2: /a $bp = 0x4720
(gdb) next
[Inferior 1 (process 9922) exited normally]
(gdb) 

正如我们所看到的,在初始化 x 和 ptr 时,堆栈指针在程序期间不会改变。我在网上查到的是x和ptr其实是存放在内存栈段的红色区域的。

然而,让我感到困惑的部分是:首先,我们声明 x 并将其设置为 10。x 的地址是:0x7fffffffdffc。然后我们初始化一个指向 x 的指针 ptr,导致 ptr 与 x 的地址具有相同的值。然而,引起我注意的是指针本身的地址:0x7ffffffffe0f0 比 x 的地址(e0f0-dffc = 4)大 4 个字节,这与我对堆栈的了解相矛盾,它在记忆,而不是向上。
红色区域的行为是否与堆栈不同?

4

0 回答 0