4

I found some code today that confused me. It did something like this:

#include <stdio.h>

int main(int argc, char **argv) {
    int x = 5;
    int foo[x];

    foo[0] = 33;
    printf("%d\n", foo[0]);
    return 0;
}

My Question is why does this work?

The array foo is on the stack so how could it be expanded by x?

I would have expected some thing like this:

#include <stdio.h>

int main(int argc, char **argv) {
    int x = 5;
    int foo[] = malloc(sizeof(int)*x);

    foo[0] = 33;
    printf("%d\n", foo[0]);
    free(foo);
    return 0;
}

Not that it is prettier or something but, I just wonder.

4
  • 1
    It's called a Variable Length Array (VLA). It's part of C since C99. Commented Jul 27, 2015 at 13:34
  • 1
    This is new in C99. I was also astonished when saw this first time. It is not normal for C way of "thinking". At least, it is not good idea to put (big) arrays in stack. Commented Jul 27, 2015 at 13:48
  • That is the better version of alloca. (there are differences in persistence, however) Commented Jul 27, 2015 at 13:54
  • KISS-Answer: because c99 rules :) Commented May 3, 2017 at 12:07

2 Answers 2

9

The snippet

int foo[x];

is talking advantage of something called VLA (Variable length array) feature. It was introduced in C99 standard, just to be made an optional feature in C11.

This way, we can create an array data structure, whose length is given (supplied) at run-time.

Point to note, though created at runtime, gcc allocates the VLAs on stack memory (unlike the dynamic memory allocation from heap memory).

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks that explains it. We have to be gcc 2.9.5 compatible couse we have platforms with a 386 processor so VLA will not work ;). Thanks.
@maxbit89 gcc has always had an extension to do variable-length arrays (although with different behaviour to Standard C ones)
2

The array foo is on the stack so how could it be expanded by x?

gcc simply moves the stack pointer:

subq    %rax, %rsp

Link to full example with assembly output

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.