c - 如何检测程序虚拟空间中的堆栈顶部



我正在尝试估计我的程序堆栈范围的跨度。我的策略是假设由于堆栈向下增长,我可以为当前堆栈帧创建一个局部变量,然后使用其地址作为参考。

 int main()
 {
   //Now we are in the main frame.
   //Define a local variable which would be lying in the top of the stack
    char a;
   //Now define another variable
    int b; //address should be lower assuming stack grows downwards
   //Now estimate the stack size by rlimit
   struct rlimit stack_size;
   getrlimit(RLIMIT_STACK,&stack_size);
   //A crude estimate would be stack goes from &a to &a - stack_size.rlim_cur
   printf("%p n",&a);
   printf("%p n",&b);
   printf("stack spans from %u to %u",&a,&a - stack_size.rlim_cur);
   return 0;
 }

有趣的是,当我使用 gdb 调试 a 和 b 的值地址时,b 的地址比 a 的值更高。此外,堆栈指针始终保持在 中的同一位置。

 0xbfca65f4 
 0xbfca660f
 Stack spans from 0xbfca65f4 to 0xbbca65f4.
 ebx            0xb7faeff4  -1208291340
 esp            0xbffff670  0xbffff670

谁能理解我哪里出错了?提前感谢!

这种方法大多有效; 你的错误只是在同一调用帧中检查ab。编译器没有理由按照您在堆栈上期望的方式对自动变量进行排序;它可能会出于数据局部性或对齐目的选择它们的顺序。

如果您比较main中一个自动对象的地址和单独的调用帧中另一个自动对象的地址(确保它不是可能内联到main中!),那么您应该获得更接近预期的结果。

最新更新