开发者

Memory assignment of local variables

开发者 https://www.devze.com 2022-12-25 05:11 出处:网络
void function(int a, int b, int c) { char buffer1[5]; char buffer2[10]; } We must remember that memory can only
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 ou开发者_JAVA百科r 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?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号