x86 64 Bit Stack Boundaries


While inspecting disassembled code on my Macbook Pro, I couldn’t figure out why the stack allocated so much space when I only requested a little. After some investigation into GCC I figured it out.

According to Apple’s developer documentation on GCC, “If 
-mpreferred-stack-boundary

is not specified, the default is 4 (16 bytes or 128 bits).” That means that the stack will always allocate chunks in factors of 16 (2^4) unless you specify otherwise.

That means that the following code

int main(int argc, char **argv) {
        char buf[1];
        return 0;
}

Translates to allocating 16 bytes on the stack even though it’s only 1 byte.

...
0x0000000100000ef2 :    sub    rsp,0x10 # 16 bytes
...

Update
This is not specific to Mac, all 64 bit platforms use this stack alignment. Here is the Windows documentation and here is the Linux documentation. Thanks Pascal!

6 Comments x86 64 Bit Stack Boundaries

  1. phil

    I was doing the same just to see and I got this

    0x7fff71022d18 : “”
    0x7fff71022d19 : “”
    0x7fff71022d1a : “”
    0x7fff71022d1b : “”
    0x7fff71022d1c : “”
    0x7fff71022d1d : “”
    0x7fff71022d1e : “”
    0x7fff71022d1f : “”

    which are only 8 bytes. I just compiled with the option
    gcc -g3 test.c

    did you made something special ?

    Reply
  2. phil

    yes, i am, I checked after to be sure that GDB was well configured as well.

    (gdb) show architecture
    The target architecture is set automatically (currently i386:x86-64)

    Reply
  3. phil

    Otherwise I read mostly the entire blog,
    but you should sometimes be a bit more precise, there are some stuff that you come up with .. without explaining anything … which is hard for the reader to understand .. but nice work.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>