-2

A very simple code to test VLA on gcc works fine on gcc-4.2.9 (Raspbian), but not on gcc-6.2.0 (Ubuntu). I am surprised. Though it compile without error, the output is not proper.

Code:

    int len, i;
    int test[len];

    scanf("%d",&len);
    for(i=0;i<=len;i++){
            test[i]=i*i;
            printf("%d\t",test[i]);}

    printf("\n");
    return 0;

Argument:

8

Output:

With 4.2.9 (Raspbian),

0       1       4       9       16      25      36      49      64

With 6.2.0 (Ubuntu),

0       1       4       9       16      1

It doesn't even reach to the count of 8. I am surprised. The same code works if I hard code the value of len.

0       1       4       9       16      25      36      49      64

Any idea about what is possibly going wrong?

melpomene
  • 84,125
  • 8
  • 85
  • 148
  • 1
    This isn't really a Unix & Linux question. This sort of faulty C programming can be done on any operating system. (-: – JdeBP Jan 28 '17 at 14:33
  • 2
    Is this an interview question - tell us what is wrong with this program? An array declared as `int test[len]` has valid indices 0 ... len-1 so you are overunning the end of the array. –  Jan 28 '17 at 14:43
  • 8
    `len` isn't initialized before VLA is defined. – myaut Jan 28 '17 at 14:45

1 Answers1

2
int len, i;
int test[len];

You're doing test[len], but at this point len hasn't been initialized. Reading from an uninitialized variable has undefined behavior.

To fix this, initialize len before using it:

if (scanf("%d",&len) != 1) {
    // handle error
}
int test[len];

And in the rest of your code, use i<len instead of i<=len because otherwise you'd access len+1 elements where only len exist.

melpomene
  • 84,125
  • 8
  • 85
  • 148