Friday, June 1, 2007

How to find address of stack top : C

In technical interviews, sometimes candidates are asked how they would find the address of the top of the stack in their system by programming in C. One simple program that should work mostly is:

int main()
{
int i;
printf("Top of the stack is %p", &i);
return 0;
}

As local variables are stored on stack, this would give an approximate top of stack. There can be variations of this program that are also few-liners like above and give more accurate results. Any more example piece of code to find stack top?

3 comments:

TemporalBeing said...

More accurate - at least for the Intel x86 series processors:

#include <stdio.h>
int main(int argc,char* argv[])
    {
    unsigned int i;
    __asm mov i, esp
    printf("stack head: 0x%0X\n",i);
    return 0;
    }

The above code works with the Visual Studios 2005 VC++ compiler, and is for 32-bit software. 16-bit software would need to reference 'sp' (Stack Pointer) instead of 'esp' (Extended Stack Pointer); and 64-bit software would need to (a) change 'unsigned int' to a larger type (e.g. possibly size_t) and reference lsp (Long Stack Pointer).

Anonymous said...

the above code is not just C. it uses assembly instructions!

Amit G said...

How can find stack bottom?
or data section start and end?