Search code examples
carraysvariable-length-array

Array declaration inside a function


Is it safe to write code like below?

void func(int v[], int size) {
 int array_local[size];

 for(int i = 0; i < size; i++) array_local[i] = v[i];

 /*
 Other stuff...
 */

}

Or could I stumble upon some kind of error?


Solution

  • Yeah this is perfectly fine and valid on and above C99. It is called VLA.

    To be on safer side, you should put a check on the value of size before using it as the number of elements of the array. As you've got the size defined as int, you should prohibit passing a value of say -5 to size.

    That said, for the remaining part of the code (as a general suggestion)

    1. v[i] should not cause in memory overrun.
    2. The array is local to the function. You should never try returning the address of the array (Either through a pointer or through return statement).