0

I am trying to understand the layout of the stack and how memory is allocated.

I have the following program and I want to know the starting address of the buffer array, if suppose the stack starts at address 12000 (for instance).

void function( int a, int b ) {     
    char buffer[ 512 ]; 
} 

void main() {
    function( 1, 2 );
}
7
  • 1
    You'll have to compiler the code and inspect the binary (or print out the address in function). There's nothing in standard C that will let you calculate that address, it's completely compiler/platform dependent. Commented Oct 26, 2014 at 18:50
  • @1336087 Stacks usually grow downwards, and you haven't considered main's call of function (and it depends on how big addresses are). Commented Oct 26, 2014 at 18:53
  • "I want to know the starting address of the buffer array" You can't, because you don't know what your particular version of your particular compiler decides to do with your particular program at your particular optimization level at this particular day of the week. Maybe it doesn't allocate any space for buffer at all because it's unused. Or maybe it allocates it on the heap because it's Sunday, and because it can. Commented Oct 26, 2014 at 18:55
  • I am using Fedora 32-bit. Will gdb help me in getting to know the full stack? Commented Oct 26, 2014 at 18:58
  • @ooga: It is architecture specific. Commented Oct 26, 2014 at 19:06

2 Answers 2

1

The address of a non-static local variable in a function depends on the state of the stack (the value of the SP register) at the point in execution when the function is invoked.

In simple words, buffer may have a different address every time function is invoked.

Having emphasized that, you can use either one of the following options:

printf("%p", buffer); // applicable only for arrays
printf("%p",&buffer); // applicable for arrays and for non-arrays
Sign up to request clarification or add additional context in comments.

2 Comments

So in the layout of the stack, where exactly the buffer address starts? Is it right at the start or somewhere in between or varies depending on the architecture and compiler?
@user3257977: Like I said in the answer, the address of the buffer may be different every time the function is invoked.
0

You can show the addresses used at run time

#include <stdio.h>

void function( int a, int b ) {
    int c;
    char buffer[ 512 ]; 
    int d;
    printf ("Address of a is %p\n", &a);
    printf ("Address of b is %p\n", &b);
    printf ("Address of c is %p\n", &c);
    printf ("Address of d is %p\n", &d);
    printf ("Address of buffer is %p\n", buffer);
} 

void main() {
    function( 1, 2 );
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.