C语言静态与动态内存分配疑问:变长数组的内存分配方式
Great question—this is a super common point of confusion, so let's break it down clearly.
The code snippet int n = 5; int arr[n]; defines a Variable-Length Array (VLA), a feature introduced in the C99 standard. Here's exactly how it works:
Memory Location: VLAs are almost always allocated on the stack—the same region of memory used for regular local variables like
int x;. When your program enters the scope where the VLA is defined, the runtime calculates the required space (using the value ofnat that exact moment) and reserves it on the stack. When you exit the scope (like when the function returns), this stack space is automatically reclaimed—no manualfree()calls needed, unlike heap-allocated memory.Key Differences from Other Allocation Types:
- vs. Static Allocation: Static arrays (like
int arr[5];where the size is a compile-time constant) have their size fixed before the program runs. They might live in static storage (if declared withstatic) or the stack (if a local non-static array), but their size is always known at compile time. VLAs can't be statically allocated because their size is determined at runtime. - vs. Dynamic Allocation (
malloc/free): Heap-allocated memory persists until you explicitlyfree()it, and you have full control over its lifetime. VLAs are tied directly to their scope—they vanish automatically when you leave the block they're defined in. Also, stack space is usually much smaller than the heap, so large VLAs can easily cause stack overflow crashes.
- vs. Static Allocation: Static arrays (like
Quick Compiler Note: Not all compilers support VLAs by default. For example, Microsoft Visual Studio's C compiler doesn't implement C99 VLAs, while GCC and Clang do support them fully.
内容的提问来源于stack exchange,提问作者stackUnderflow

