Note that there are some explanatory texts on larger screens.

plurals
  1. POVariable order and memory addressing in stack memory
    primarykey
    data
    text
    <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/1102049/order-of-local-variable-allocation-on-the-stack">Order of local variable allocation on the stack</a> </p> </blockquote> <p>(C program on x86_64 Linux) I am trying to understand the way variables are assigned to stack memory. As I understand it, variables in a stack frame move toward lower memory addresses. The program below shows this.</p> <pre><code>int main() { int i = 6; char buffer[8]; return 0; } </code></pre> <p>Program was compiled as: gcc -g prog.c</p> <p>Debugging shows:</p> <pre><code>(gdb) x/x &amp;i 0x7fffffffe04c: 0x00000006 (gdb) x/x buffer 0x7fffffffe040: (random data) </code></pre> <p>The character array has a lower memory address than the integer i variable. My question is how come when the order of declarations are reversed as seen below, the integer variable i is still at a memory address greater than the character array?</p> <pre><code>int main() { char buffer[8]; int i = 6; return 0; } (gdb) x/x &amp;i 0x7fffffffe04c: 0x00000006 (gdb) x/x buffer 0x7fffffffe040: (random data) </code></pre> <p>This issue does not seem to occur for the ordering of say strictly single integer variables. If the order of integer declarations were switched, the earliest declared would have a higher memory address in the stack frame. The concern here is why this occurs for the character array. I have read this answer here in <a href="https://stackoverflow.com/questions/1102049/order-of-local-variable-allocation-on-the-stack">another post</a> but I am wondering if anyone has a definitive explanation on this one.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload