Question

void function(int a, int b, int c) {
   char buffer1[5];
   char buffer2[10];
}

We must remember that memory can only be addressed in multiples of the word size. A word in our case is 4 bytes, or 32 bits. So our 5 byte buffer is really going to take 8 bytes (2 words) of memory, and our 10 byte buffer is going to take 12 bytes (3 words) of memory. That is why SP is being subtracted by 20.

Why it's not ceil((5+10)/4)*4=16?

Was it helpful?

Solution

Because individual variables should be aligned. With your proposed formula, you'd align only the first variable on the stack, leaving following variables unaligned, which is bad for performance.

This is also known as "packing" and can be done in C/C++ with pragmas, but is only useful in very specific cases and can be dangerous both for performance and as a cause of potential runtime traps. Some processors will generate faults on unaligned accesses at runtime, which will crash your program.

OTHER TIPS

The variables on your architecture are aligned individually. buffer1 gets rounded up to 8 and buffer2 to 12 so that both of their starting addresses are 4-byte aligned. So 8+12 = 20.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top