-4

The following snippet compiles properly using standard gcc. What are possible pitfalls here? --especially for kernel level development.

int n;

f(){n=2;}
g(){int b[n];}

main(){
        int a[n];
        f();
        g();
}
Ali Abbasinasab
  • 382
  • 3
  • 13
  • 1
    It doesn't compile (`2 : error: variably modified 'c' at file scope`). – cremno Aug 05 '15 at 23:06
  • n is 0 at compile time and int c[n] will be a zero length array because structures are resolved at compile time. – B. Nadolson Aug 05 '15 at 23:07
  • Since kernel structs often have to outlive the calls that raise them, there would seem to be limited usefulness, even if allocated on a kernel stack, (of limited size anyway). Of couse, a global VLA does not make sense, (or compile), anyway:( – Martin James Aug 05 '15 at 23:21
  • These are no standard compliant function definitions. They will _not_ compiler without warning with gcc 5.1+ – too honest for this site Aug 06 '15 at 00:28

1 Answers1

5

It is invalid code because variable length arrays may not have sizes equal to 0. In your example, file-scope variable n is initialized by 0.

This array

    int a[n];

has zero size because variable n was zero initialized as having static storage duration.

To get a valid program you should write something like the following

#include <stdio.h>

int n;

void f( void ){n=2;}
void g( void ){int b[n]; printf( "sizeof( b ) = %zu\n", sizeof( b ) ); }

int main( void )
{
        f();
        int a[n];
        printf( "sizeof( a ) = %zu\n", sizeof( a ) );
        g();
}    

Take into account that VLA(s) were introduced in C99 and at the same time the Standard suppressed the default return type int of functions.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335