스택 변수 크기가 동적으로 가능한가요?

trymp의 이미지

linux GCC 환경에서 C언어 사용할때

가령 아래와 같이 이런식으로 스택배열의 크키를 정해줄수있나요?

저는 malloc 같은걸로만 동적으로 정해주고 스택변수 크기는 정적으로 정해지는 줄 알았는데요

제가 잘못 안건가요? 조언해주시면 감사하겠습니다.

void func1(int len)

{
char arr[len];

.
.
.

}

라스코니의 이미지

놀랍게도(?) 최근 컴파일러에서는 된다고 하네요.

disassss의 이미지

디스어셈블해보면 아마 malloc() 호출하는 코드로 들어가 있을 겁니다.

익명 사용자의 이미지

malloc으로 구현될 필요는 없습니다.

예컨대 x86_64 gcc 12.2에서...

void call_with_VLA(int size, void (*f)(int size, int array[])) {
        int vla[size];
 
        f(size, vla);
        return;
}

call_with_VLA:
        pushq   %rbp
        movslq  %edi, %rax
        movq    %rsi, %rdx
        leaq    15(,%rax,4), %rax
        andq    $-16, %rax
        movq    %rsp, %rbp
        subq    %rax, %rsp
        movq    %rsp, %rsi
        call    *%rdx
        leave
        ret

컴파일 옵션은 -std=c99 -pedantic -pedantic-errors -O3 입니다.

사실 gcc는 alloca 호출도 inlined code 처리해요. VLA라고 다를 이유는 없죠.

trymp의 이미지

^^

익명 사용자의 이미지

C99 표준에 추가된 Variable-length arrays 라는 기능입니다.
아래와 같은 함수를 정의할 수 있게 해 주지요.

#include <stdio.h>
 
static void reverse_nums(int size, int array[]) {
        for (int i = 0; i != size; ++i) {
                scanf("%d", &array[i]);
        }
 
        for (int i = size - 1; i >= 0; --i) {
                printf("%d ", array[i]);
        }
        puts("");
 
        return;
}
 
void call_with_VLA(int size, void (*f)(int size, int array[])) {
        int vla[size];
 
        f(size, vla);
        return;
}
 
int main() {
        call_with_VLA(10, reverse_nums);
 
        return 0;
}

생각해 보면, alloca 같은 기능도 있는데 스택 배열의 크기가 동적이지 못할 이유가 없죠.

https://man7.org/linux/man-pages/man3/alloca.3.html

물론 스택의 특성상 너무 큰 메모리를 잡으려 하는 건 지양하는 것이 좋습니다.

======

p.s. Variable-length arrays 지원은 C11부터 optional이 되고 맙니다. __STDC_NO_VLA__이 1로 정의되어 있는 경우 VLA가 지원되지 않습니다.