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();
}
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();
}
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.