Dynamic array allocation on stack in C

user3769509 picture user3769509 · Oct 18, 2014 · Viewed 15.8k times · Source

I just did a experiment yesterday, and find something confusing:

#include <stdio.h>

int main()
{
    int j;
    scanf("%d",&j);
    const int i = j;
    int arr[i];
    return 0;
}

The number j is read from keyboard and it’s used to allocate the array arr on the stack.

The compiler does not even know the size of the array at compile time (initializes j to 0?), but there is no compilation error. How is it possible?

Answer

user3920237 picture user3920237 · Oct 18, 2014

Variable length arrays were added to C99. It's described in the C99 rationale:

6.7.5.2 Array declarators

C99 adds a new array type called a variable length array type. The inability to declare arrays whose size is known only at execution time was often cited as a primary deterrent to using C as a numerical computing language. Adoption of some standard notion of execution time arrays was considered crucial for C’s acceptance in the numerical computing world.

The number of elements specified in the declaration of a variable length array type is a runtime expression. Before C99, this size expression was required to be an integer constant expression.

There is no "dynamic array allocation on the stack". The array size has to be specified at the declaration.

Some compilers, like GCC allow them as an extension in C90 (in GCC, this is equivalent to ansi and C89) mode and C++. In these cases, you will get a warning (-Wpedantic) or an error (-Werror or -pedantic-errors). Consult the documentation for your compiler.

Per @Deduplicator's comment, you seem to have a misconception. Variable length arrays cannot be declared static.

§ 6.7.6.2

10 EXAMPLE 4 All declarations of variably modified (VM) types have to be at either block scope or function prototype scope. Array objects declared with the _Thread_local, static, or extern storage-class specifier cannot have a variable length array (VLA) type. However, an object declared with the static storage-class specifier can have a VM type (that is, a pointer to a VLA type). Finally, all identifiers declared with a VM type have to be ordinary identifiers and cannot, therefore, be members ostructures or unions.

This means that static storage and automatic storage are mutually exclusive.