CKTIS / C
Variable-length array (VLA) in C
A local buffer declared as `int tmp[n]` gets its length at run time. Validate the bound before declaring it, respect its lifetime, and account for optional automatic VLA support in C23.
Version: ISO C23; implementation support may vary
Syntax
int tmp[n];Inside a function, int tmp[n]; with an int parameter n declares a variable-length array (VLA). Unlike int tmp[8];, its element count is determined when execution reaches the declaration. Check n before the declaration: it must be positive. Reaching the declaration with n <= 0 causes undefined behavior.
tmp has automatic storage duration: its lifetime starts when execution reaches the declaration and ends when execution leaves its scope. Do not return a pointer to one of its elements or use such a pointer after that point. Changing n does not resize the existing array. sizeof tmp gives its size in bytes; sizeof tmp / sizeof tmp[0] gives its element count.
C23 makes VLA objects with automatic storage duration optional. If __STDC_NO_VLA__ is defined as 1, the implementation does not support such objects as tmp. C23 still requires support for variably modified types, such as a pointer to a VLA, and for VLA objects with allocated storage duration. In C11 and C17, the same macro could indicate lack of support for both VLAs and variably modified types.
C does not require a stack, but automatic VLAs are often placed on one. A large buffer can exhaust it, and the declaration gives you no return value to check for allocation failure. Do not use unchecked input as the bound: set a small, platform-appropriate maximum or use a fixed-size array. For larger buffers, consider malloc: check for overflow when computing the byte count, handle NULL, and release the memory with free.
Examples
#include <stdio.h>
#include <stdlib.h>
static int print_buffer(int n)
{
if (n <= 0 || n > 8) {
return EXIT_FAILURE;
}
int tmp[n];
for (int i = 0; i < n; ++i) {
tmp[i] = i + 1;
}
printf("count=%zu last=%d\n", sizeof tmp / sizeof tmp[0], tmp[n - 1]);
return EXIT_SUCCESS;
}
int main(void)
{
return print_buffer(4);
}
Result
count=4 last=4
`print_buffer(4)` checks that `n` is between `1` and `8`, then creates a four-element `tmp` and fills it with `1` through `4`. The expected output is `count=4 last=4`.
Related lessons
- C · Lesson 68 · Advanced · Version: 3