gcc/g++ 如何处理变长数组

问题描述 投票:0回答:0

这里是一些简单的C++代码。我在

test_func
中定义了一个变长数组。我想知道数组
arr
rbp
寄存器之间的关系。

void test_func(int m, int n) {
    int arr[m];
    for(int i = 0; i < m; ++i) {
        arr[i] = m;
    }
    cout << "ok";
}
int main() {
   
    int m = 30, n = 12;
    test_func(m, n);
    return 0;
}

我用 gdb 查看他们的地址,但我一无所获。 enter image description here

然后我用

g++ -E test.cpp -o test.i , g++ -S test.i -o test.S
。我发现了一些奇怪的汇编代码。

_Z9test_funcii:
.LFB1559:
    pushq   %rbp
    .seh_pushreg    %rbp
    pushq   %r12
    .seh_pushreg    %r12
    subq    $40, %rsp
    .seh_stackalloc 40
    leaq    128(%rsp), %rbp
    .seh_setframe   %rbp, 128
    .seh_endprologue
    movl    %ecx, -64(%rbp)
    movl    %edx, -56(%rbp)
    movq    %rsp, %rax
    movq    %rax, %r8
    movl    -64(%rbp), %eax
    cltq
    subq    $1, %rax
    movq    %rax, -112(%rbp)
    movq    %rax, %rdx
    addq    $1, %rdx
    movq    %rdx, %r11
    movl    $0, %r12d
    movq    %rax, %rdx
    addq    $1, %rdx
    movq    %rdx, %r9
    movl    $0, %r10d
    addq    $1, %rax
    salq    $2, %rax
    addq    $15, %rax
    shrq    $4, %rax
    salq    $4, %rax
    call    ___chkstk_ms
    subq    %rax, %rsp
    movq    %rsp, %rax
    addq    $3, %rax
    shrq    $2, %rax
    salq    $2, %rax
    movq    %rax, -120(%rbp)
    movl    $0, -100(%rbp)
.L3:
    movl    -100(%rbp), %eax
    cmpl    -64(%rbp), %eax
    jge .L2
    movq    -120(%rbp), %rdx
    movl    -100(%rbp), %eax
    cltq
    movl    -64(%rbp), %ecx
    movl    %ecx, (%rdx,%rax,4)
    addl    $1, -100(%rbp)
    jmp .L3
.L2:
    movq    %r8, %rsp
    nop
    leaq    -88(%rbp), %rsp
    popq    %r12
    popq    %rbp
    ret
    .seh_endproc
    .def    __main; .scl    2;  .type   32; .endef
    .globl  main
    .def    main;   .scl    2;  .type   32; .endef
    .seh_proc   main

想知道

arr
在栈上的位置和
rbp
寄存器的关系

c++ gcc stack g++
© www.soinside.com 2019 - 2024. All rights reserved.