0

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!

as3rdaccount
  • 3,711
  • 12
  • 42
  • 62
  • Bad assumption unless you _know_ which environment you're running in: http://stackoverflow.com/questions/664744/what-is-the-direction-of-stack-growth-in-most-modern-systems/664779#664779. In addition, I don't think C mandates that the order of definition controls where something sits in the stack frame. C only guarantees order within structures. Possibly a better way is to create `b` one level down (in a called function). – paxdiablo Jan 31 '13 at 02:44
  • I'm fairly sure your stack size calculation in itself is wrong, as the stack is highly unlikely to end somewhere that isn't an even page (hex number ending with 000) - but that may be because some space has already been used by the time you get to main. Other than that and "order between variables in function is not guaranteed", I'm not sure I understand what your question is... – Mats Petersson Jan 31 '13 at 03:10

1 Answers1

2

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.

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711