I am trying to draw a stack where the bottom of the process is 0xffff. The program is simple:
int main() {
char c;
int i;
double d;
int iArr[4];
return 0;
}
When I created a program for a sample of what the addresses could look like, I got:
iArr[0]: 0x7ffce0c79970
iArr[1]: 0x7ffce0c79974
iArr[2]: 0x7ffce0c79978
iArr[3]: 0x7ffce0c7997c
d: 0x7ffce0c79980
i: 0x7ffce0c79988
c: 0x7ffce0c7998f
The sizeof() function says that integers are 4 bytes, so why does i go from 88 to 88e? Also, if the bottom of the process is assumed to be 0xffff, would c start at 0xffff or 0xfffe?
You're going to need to consider alignment (alignof
) as well as size (sizeof
) because certain types must be aligned on specific memory addresses or the CPU can't deal.
For example, int
must be on an address that's a multiple of 4 bytes, double
on a multiple of 8, etc. while char
being just one byte can go anywhere.
If you visualize the stack you see it as this:
| | | | | | | | |
+----+----+----+----+----+----+----+----+
...9970 | iArr[0] | iArr[1] |
+----+----+----+----+----+----+----+----+
...9978 | iArr[2] | iArr[3] |
+----+----+----+----+----+----+----+----+
...9980 | d |
+----+----+----+----+----+----+----+----+
...9988 | i | | | | c |
+----+----+----+----+----+----+----+----+
Which makes sense since the stack tends to grow down, that is earlier entries have higher memory addresses. So c
gets the highest address, then i
gets the next possible highest address, accounting for alignment, and so on. The iArr
array is allocated as a contiguous chunk of memory at the highest possible alignment, but the indexes work in reverse order to the stack, they always count up, so that looks strange but makes sense too.