编译器为 arm-none-eabi-gcc v10.3.1,优化等级为 -O0
示例代码如下
rt_thread_t s_test_thread = NULL;
void test_func(void)
{
char array[10] = {0};
array[1] = 1;
array[9] = 9;
uint32_t num = 10;
char buf[32] = {0};
buf[15] = 15;
buf[31] = 31;
}
void test_func2(void)
{
char array[10] = {0};
}
void test_func3(void)
{
char array[200] = {0};
}
void test_thread(void *args)
{
test_func();
test_func2();
test_func3();
while (1) {
sleep(1);
}
}
int main(void)
{
s_test_thread = rt_thread_create("test",
test_thread,
NULL,
4 * 1024,
15,
10);
rt_thread_startup(s_test_thread);
while (1) {
sleep(1);
}
return 0;
}
反汇编代码如下
void test_func(void)
{
8000b80: b480 push {r7}
8000b82: b08d sub sp, #52 ; 0x34
8000b84: af00 add r7, sp, #0
char array[10] = {0};
8000b86: 2300 movs r3, #0
8000b88: 623b str r3, [r7, #32]
8000b8a: f107 0324 add.w r3, r7, #36 ; 0x24
8000b8e: 2200 movs r2, #0
8000b90: 601a str r2, [r3, #0]
8000b92: 809a strh r2, [r3, #4]
array[1] = 1;
8000b94: 2301 movs r3, #1
8000b96: f887 3021 strb.w r3, [r7, #33] ; 0x21
array[9] = 9;
8000b9a: 2309 movs r3, #9
8000b9c: f887 3029 strb.w r3, [r7, #41] ; 0x29
uint32_t num = 10;
8000ba0: 230a movs r3, #10
8000ba2: 62fb str r3, [r7, #44] ; 0x2c
char buf[32] = {0};
8000ba4: 2300 movs r3, #0
8000ba6: 603b str r3, [r7, #0]
8000ba8: 1d3b adds r3, r7, #4
8000baa: 2200 movs r2, #0
8000bac: 601a str r2, [r3, #0]
8000bae: 605a str r2, [r3, #4]
8000bb0: 609a str r2, [r3, #8]
8000bb2: 60da str r2, [r3, #12]
8000bb4: 611a str r2, [r3, #16]
8000bb6: 615a str r2, [r3, #20]
8000bb8: 619a str r2, [r3, #24]
buf[15] = 15;
8000bba: 230f movs r3, #15
8000bbc: 73fb strb r3, [r7, #15]
buf[31] = 31;
8000bbe: 231f movs r3, #31
8000bc0: 77fb strb r3, [r7, #31]
}
8000bc2: bf00 nop
8000bc4: 3734 adds r7, #52 ; 0x34
8000bc6: 46bd mov sp, r7
8000bc8: bc80 pop {r7}
8000bca: 4770 bx lr
void test_func2(void)
{
8000bcc: b480 push {r7}
8000bce: b085 sub sp, #20
8000bd0: af00 add r7, sp, #0
char array[10] = {0};
8000bd2: 2300 movs r3, #0
8000bd4: 607b str r3, [r7, #4]
8000bd6: f107 0308 add.w r3, r7, #8
8000bda: 2200 movs r2, #0
8000bdc: 601a str r2, [r3, #0]
8000bde: 809a strh r2, [r3, #4]
}
8000be0: bf00 nop
8000be2: 3714 adds r7, #20
8000be4: 46bd mov sp, r7
8000be6: bc80 pop {r7}
8000be8: 4770 bx lr
void test_func3(void)
{
8000bea: b580 push {r7, lr}
8000bec: b0b2 sub sp, #200 ; 0xc8
8000bee: af00 add r7, sp, #0
char array[200] = {0};
8000bf0: 2300 movs r3, #0
8000bf2: 603b str r3, [r7, #0]
8000bf4: 1d3b adds r3, r7, #4
8000bf6: 22c4 movs r2, #196 ; 0xc4
8000bf8: 2100 movs r1, #0
8000bfa: 4618 mov r0, r3
8000bfc: f03b fd82 bl 803c704
}
8000c00: bf00 nop
8000c02: 37c8 adds r7, #200 ; 0xc8
8000c04: 46bd mov sp, r7
8000c06: bd80 pop {r7, pc}
疑问:
在 test_func 函数中,用到的栈空间为 46(10 + 4 + 32)字节,却预留 52 字节的空间,这多出来的 6 字节的用途是什么?
在 test_func2 函数中,用到的栈空间为 10 字节,却预留 20 字节的空间,这多出来的 10 字节的用途是什么?
在 test_func3 函数中,用到的栈空间为 200 字节,预留 200 字节的空间,刚刚好,和上面的两个函数不一样,这是为什么呢?
更多回帖