Note that there are some explanatory texts on larger screens.

plurals
  1. POOrder of local variable allocation on the stack
    primarykey
    data
    text
    <p>Take a look at these two functions:</p> <pre><code>void function1() { int x; int y; int z; int *ret; } void function2() { char buffer1[4]; char buffer2[4]; char buffer3[4]; int *ret; } </code></pre> <p>If I break at <code>function1()</code> in <code>gdb</code>, and print the addresses of the variables, I get this:</p> <pre><code>(gdb) p &amp;x $1 = (int *) 0xbffff380 (gdb) p &amp;y $2 = (int *) 0xbffff384 (gdb) p &amp;z $3 = (int *) 0xbffff388 (gdb) p &amp;ret $4 = (int **) 0xbffff38c </code></pre> <p>If I do the same thing at <code>function2()</code>, I get this:</p> <pre><code>(gdb) p &amp;buffer1 $1 = (char (*)[4]) 0xbffff388 (gdb) p &amp;buffer2 $2 = (char (*)[4]) 0xbffff384 (gdb) p &amp;buffer3 $3 = (char (*)[4]) 0xbffff380 (gdb) p &amp;ret $4 = (int **) 0xbffff38c </code></pre> <p>You'll notice that in both functions, <code>ret</code> is stored closest to the top of the stack. In <code>function1()</code>, it is followed by <code>z</code>, <code>y</code>, and finally <code>x</code>. In <code>function2()</code>, <code>ret</code> is followed by <code>buffer1</code>, then <code>buffer2</code> and <code>buffer3</code>. Why is the storage order changed? We're using the same amount of memory in both cases (4 byte <code>int</code>s vs 4 byte <code>char</code> arrays), so it can't be an issue of padding. What reasons could there be for this reordering, and furthermore, is it possible by looking at the C code to determine ahead of time how the local variables will be ordered?</p> <p>Now I'm aware that the ANSI spec for C says nothing about the order that local variables are stored in and that the compiler is allowed to chose its own order, but I would imagine that the compiler has rules as to how it takes care of this, and explanations as to why those rules were made to be as they are.</p> <p>For reference I'm using GCC 4.0.1 on Mac OS 10.5.7</p>
    singulars
    1. This table or related slice is empty.
    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.
 

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