Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can static array in C taking size in runtime?

Tags:

c

I am mindblown by this small code:

#include <stdio.h>

    int main()
    {
        int limit = 0;
        scanf("%d", &limit);
        int y[limit];
        
        for (int i = 0; i<limit; i++ ) {
            y[i] = i;
        }
        
        for (int i = 0; i < limit; i++) {
            printf("%d ", y[i]); 
        }
    
        return 0;
    }

How on earth this program is not segment-faulting as limit (size of the array) is assigned at runtime only?

Anything recently changed in C? This code shouldn't work in my understanding.

like image 625
kishoredbn Avatar asked Aug 09 '26 15:08

kishoredbn


1 Answers

int y[limit]; is a Variable Length Array (or VLA for short) and was added in C99. If supported, it allocates the array on the stack (on systems having a stack). It's similar to using the machine- and compiler-dependent alloca function (which is called _alloca in MSVC):

Example:

#include <alloca.h>
#include <stdio.h>

int main()
{
    int limit = 0;
    if(scanf("%d", &limit) != 1 || limit < 1) return 1;

    int* y = alloca(limit * sizeof *y); // instead of a VLA

    for (int i = 0; i<limit; i++ ) {
        y[i] = i;
    }

    for (int i = 0; i < limit; i++) {
        printf("%d ", y[i]);
    }
} // the memory allocated by alloca is here free'd automatically

Note that VLA:s are optional since C11, so not all C compilers support it. MSVC for example does not.

like image 77
Ted Lyngmo Avatar answered Aug 11 '26 04:08

Ted Lyngmo