Author Topic: Local variables - stack alignment  (Read 9621 times)

Offline Mixolydian

  • Jr. Member
  • *
  • Posts: 21
Local variables - stack alignment
« on: June 03, 2014, 07:09:28 PM »
Hi, I'm just wondering about local variables.

I've written the following code:

Code: [Select]
displayMessage:
push ebp
mov ebp, esp
and esp, -16
sub esp, 4

mov dword [esp], 3

push dword dword [esp]
push message
call _printf

add esp, 4
mov esp, ebp
pop ebp
ret

And it works. But when I've looked at the output from C compilers, it seems to align the stack to 16 bytes.

So the above would be:

Code: [Select]
displayMessage:
push ebp
mov ebp, esp
and esp, -16
sub esp, 16

mov dword [esp+12], 3

push dword dword [esp+12]
push message
call _printf

add esp, 16
mov esp, ebp
pop ebp
ret

Should I be aligning the stack to 16 bytes like this or is it just something C does? Will my code run faster when my stack pointer is aligned to 16 bytes?

Offline encryptor256

  • Full Member
  • **
  • Posts: 250
  • Country: lv
  • Win64 .
    • On Youtube: encryptor256
Re: Local variables - stack alignment
« Reply #1 on: June 03, 2014, 07:44:30 PM »
Hmm... Interesting.

Maybe your cpu is 64 bit.

On 64 bit you need to align stack on 16 byte boundaries, who knows, maybe then there is need for 32 bit too.

Yes, it might run faster if stack is aligned on 16 byte boundaries.

Well, you have to investigate this alignment issue on 32 bit further.

I suggest using like C compiler does.
Encryptor256's Investigation \ Research Department.

Offline Mixolydian

  • Jr. Member
  • *
  • Posts: 21
Re: Local variables - stack alignment
« Reply #2 on: June 03, 2014, 07:49:57 PM »
I think I will do what C does and align the stack pointer to 16 byte boundaries; I was just looking for a definitive reason as to why C does this.

Offline Frank Kotler

  • NASM Developer
  • Hero Member
  • *****
  • Posts: 2667
  • Country: us
Re: Local variables - stack alignment
« Reply #3 on: June 03, 2014, 08:02:47 PM »
I "think" C does this "in case" you need a local variable aligned for SSE. Won't hurt to have "better" alignment than we need, not enough is a problem. We aren't likely to run out of stack space.

Best,
Frank