Stack alignment question

Question about which tools to use, bugs, the best way to implement a function, etc should go here. Don't forget to see if your question is answered in the wiki first! When in doubt post here.
Post Reply
tom1000000

Stack alignment question

Post by tom1000000 »

Hi,

This is probably bit of a stupid question but:

For x86 the stack is 32bit aligned. When you compile a C application local function variables are placed on the stack. What happens if the local variable is say 8 bytes? Does the compiler (GCC for example) ensure that the 8byte variable is naturally aligned? Or does GCC just put the variable on the stack unaligned.

example code:

int foo(int input)
{
int testVal;
long long testVal2; //Is this how to declare a 64bit int?

//Yes I know this is a stupid function
testVal = input;
testVal2 = (long long)testVal;

return (int)testVal2;
}


Does GCC ensure testVal2 is aligned to 8 bytes, or could it possibly be misaligned at an address which is an odd multiple of 4?
User avatar
Pype.Clicker
Member
Member
Posts: 5964
Joined: Wed Oct 18, 2006 2:31 am
Location: In a galaxy, far, far away
Contact:

Re:Stack alignment question

Post by Pype.Clicker »

maybe the best way to know is to disassemble the GCC-produced code ... but i wouldn't be surprised if GCC was even trying to have the stackframe starting at a 32-bytes boundary so that it is aligned on a cache line boundary ...

there are some "sub esp, ..." that are still weird for me ...
Peter_Vigren

Re:Stack alignment question

Post by Peter_Vigren »

What is the alignment good for? Does it go faster with it? Does an error occur otherwise? I've never understood that part really...
Tim

Re:Stack alignment question

Post by Tim »

Yes, aligned memory is faster to access. On RISC architectures, unaligned memory accesses actually generate an exception; operating systems for RISC machines handle this by doing the memory access in two halves.

On the x86 the CPU takes care of this, but unaligned memory accesses still require two accesses to the memory where only one is needed. Luckily the compiler keeps everything aligned by default.
Post Reply