Address of variable lower than address of a pointer?

0
int main(int argc  , char *argv[] ) 
{
    int value = 5;
    char buffer_one[8] , buffer_two[8];

    strcpy(buffer_one,"one");
    strcpy(buffer_two,"two");
    printf("[BEFORE] buffer_two is at %p and containt \'%s\' \n ",buffer_two,buffer_two);

    printf("[BEFORE] buffer_one is at %p and containt \'%s\' \n ",buffer_one,buffer_one);
    printf("[BEFORE] value is at %p and is %d (0x%08x)\n",&value,value,value);
}

I got this result:

[BEFORE] buffer_two is at 0x7ffd75d46720 and containt 'two' 
 [BEFORE] buffer_one is at 0x7ffd75d46710 and containt 'one' 
 [BEFORE] value is at 0x7ffd75d4670c and is 5 (0x00000005)

As you can see the address of buffer_two is higher then buffer_one (because it's pushed on the heap and and the heap goes up to higher addresses) here everything is okey.

What I don't understand why the address of the Value variable is smaller than both , I think it must be higher because variables are stored on the stack! and the stack has higher addresses than the heap!

c
pointers
stack
heap
asked on Stack Overflow Oct 21, 2015 by mohamed tehami • edited Dec 15, 2018 by Cœur

2 Answers

0

Because all three variables are defined within a function, they all live on the stack. The stack typically grows downward, so it looks like space for buffer_two was pushed onto the stack first, followed by 8 padding bytes, followed by buffer_one, followed by value.

That being said, how variables are placed on the stack is implementation defined, and could vary in the same implementation when seemingly unrelated code changes are made.

For example, on my system this code outputs the following:

[BEFORE] buffer_two is at 0xbfb16110 and containt 'two' 
 [BEFORE] buffer_one is at 0xbfb16118 and containt 'one' 
 [BEFORE] value is at 0xbfb16120 and is 5 (0x00000005)

In this case, the variables were placed on the stack in the opposite order, and without the 8 byte padding.

answered on Stack Overflow Oct 21, 2015 by dbush
0

There is no requirement for the compiler to store separate objects in any particular order (whether that storage comes from the stack, heap, or some other section of memory). It does not have to lay them out in the order in which you declared them, nor do they have to be adjacent in memory.

struct members must be laid out in the order in which they are declared, but they may or may not be adjacent; there may be "padding" bytes between members, again due to alignment requirements.

answered on Stack Overflow Oct 21, 2015 by John Bode • edited Oct 21, 2015 by Keith Thompson

User contributions licensed under CC BY-SA 3.0