How to detect the top of the stack in program virtual space

I am trying to estimate the span of my program stack range. My strategy was to assume that since the stack grows downwards, I can create a local variable to the current stack frame and then use its address as a reference.

 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;
 }

Interestingly when I use the gdb to debug the values address of a and b, address of b has a higher value than a. Also the stack pointer remains always in the same place in .

 0xbfca65f4 
 0xbfca660f
 Stack spans from 0xbfca65f4 to 0xbbca65f4.

 ebx            0xb7faeff4  -1208291340
 esp            0xbffff670  0xbffff670

Can anybody hep me understand where I am going wrong? Thanks in advance!


This approach mostly works; your mistake is just examining both a and b in the same call frame. There's no reason for the compiler to order automatic variables the way you expect on the stack; it's likely to choose their order for data locality or alignment purposes.

If you compare the address of one automatic object in main and another in a separate call frame (make sure it's not one that might get inlined into main !) then you should get results closer to what you expect.

链接地址: http://www.djcxy.com/p/80288.html

上一篇: 使用setrlimit为线程设置堆栈大小

下一篇: 如何检测程序虚拟空间中堆栈的顶部