2
int square() {
    char test[50];
}

The above code produces

square():
        push    rbp
        mov     rbp, rsp

When i change the code a little to

int square() {
    char test[150];
}

The assembly generated is

square():
        push    rbp
        mov     rbp, rsp
        sub     rsp, 40

Which is still weird because I cannot understand why it does not allocate for previous creations. I'm running at -O0 so gcc doesn't optimize it out. Why is gcc creating code for wrong sized arrays?

int square() {
    char a[50];
    char b[50];
}
square():
        push    rbp
        mov     rbp, rsp
        sub     rsp, 8

Similarly for x86

int square() {
    char a[500];
}

compiled with -m32 gives me:

square():
        push    ebp
        mov     ebp, esp
        sub     esp, 512

Where is this extra 12 bytes from? And why does -m32 have an sub instruction for char test[50] but x86_64 doesn't?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
user282909
  • 115
  • 1
  • 7
  • 1
    You are giving the compiler valid C code, but relatively useless functions. The compiler is free to omit useless stuff in the generated code -- in fact, that's one of its primary objectives (though this does vary with implementations and command line options). With a local array that isn't used, we should not have expectations. One way to make a function useful is to pass parameters and compute return values. – Erik Eidt Feb 19 '20 at 15:57
  • Did you try to put some actual code that does something useful with the array(s)? – Jabberwocky Feb 19 '20 at 16:16

1 Answers1

3

GCC is using the x86-64 System V ABI's 128-byte Red Zone below the stack pointer for the variables, only reserving some extra stack space when that's not sufficient

For the last example, GCC subs 512 to keep the stack (and the array) aligned.

The i386 System V ABI does not have a red zone so it has to reserve space for the whole array (neither does Windows x64, for that matter).

S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
  • 1
    The only 32-bit code is the very last, where the stack allocation is the full array size. The `sub rsp,8` is with two 50-byte arrays, each aligned by 16, with GCC probably wasting some extra space. (They would both fit in the red-zone but GCC doesn't do that.). – Peter Cordes Feb 19 '20 at 16:15