← Back to C Course | Chapter 12: Advanced Topics | Lesson 4 of 20

C Variable Length Arrays

What is a VLA?

A variable length array (VLA) lets you size an array using a variable's value at the moment the array is declared, instead of requiring a compile-time constant like int arr[10]. This is handy when you don't know an array's exact size until the program is already running, such as sizing a buffer to a user-provided count.

Example: What is a VLA?

c
#include <stdio.h>
int main() {
	int n = 5;
	int arr[n];
	arr[0] = 1;
	printf("%d", arr[0]);
	return 0;
}

Declaring and Using VLAs

To declare a VLA, first compute or read the size into an integer variable, then use that variable directly inside the array brackets, e.g. int n = getCount(); int values[n];. The size expression is evaluated once at the point of declaration, so changing the variable afterward does not resize the array.

Example: Declaring and Using VLAs

c
#include <stdio.h>
int main() {
	int n = 3;
	int values[n];
	for (int i = 0; i < n; i++) {
		values[i] = i * 2;
	}
	printf("%d", values[2]);
	return 0;
}

VLAs inside Functions

VLAs are especially useful inside helper functions that need a temporary buffer sized exactly to the caller's input, avoiding the need to over-allocate a fixed maximum size or call malloc() for something short-lived. The array automatically disappears when the function returns, with no manual cleanup required.

Example: VLAs inside Functions

c
#include <stdio.h>
void printBuffer(int size) {
	int buffer[size];
	buffer[0] = 99;
	printf("%d", buffer[0]);
}
int main() {
	printBuffer(5);
	return 0;
}

Memory Allocation of VLAs

Unlike malloc(), which reserves memory on the heap that persists until you explicitly free() it, a VLA is allocated on the stack and is automatically reclaimed the moment its enclosing scope ends. This makes VLAs simpler to use for short-lived buffers, since there is no risk of forgetting to free them.

Example: Memory Allocation of VLAs

c
#include <stdio.h>
void useVLA() {
	int n = 4;
	int arr[n];
	arr[0] = 1;
	printf("%d", arr[0]);
}
int main() {
	useVLA();
	return 0;
}

Limits of VLAs

Stack space is much smaller than heap space (often just a few megabytes), so declaring a VLA sized by an unchecked or attacker-controlled variable can overflow the stack and crash the program. Always validate that a VLA's requested size stays within a sane, expected bound before declaring it.

Example: Limits of VLAs

c
#include <stdio.h>
int main() {
	int n = 10;
	int arr[n];
	arr[0] = 1;
	printf("%d", arr[0]);
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.