C programming/Variable Lengt Arrays VLA

From Teknologisk videncenter
Jump to: navigation, search

From C99 variable length arrays was introduced in c.

Problems

VLA use the stack as placeholder for the array:

  • In the function read_and_process_vla() - the stack is used as storage for the array. If the array is greather than the remaining stack size - stack overflow occurs. Check stack size on Linux with the ulimit -a command
  • In the function read_and_process_novla() - the heap through malloc() is used.

Be careful when using VLA

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 
 5 float process(int n, float *vals) {
 6         for (int i=0; i < n; i++) {
 7                 printf("%f ", vals[i]);
 8         }
 9         printf("\n");
10 }
11 
12 float read_and_process_vla(int n) {
13     float vals[n];
14     for (int i = 0; i < n; ++i)
15         vals[i] = i;
16     return process(n, vals);
17 }
18 
19 float read_and_process_novla(int n) {
20     float (*vals)[n] = malloc(sizeof(float[n]));
21     for (int i = 0; i < n; ++i)
22         (*vals)[i] = i;
23     float ret = process(n, *vals);
24     free(vals);
25     return ret;
26 }
27 int main(void) {
28         printf("========================= Using VLA =========================\n");
29         read_and_process_vla(10);
30         read_and_process_vla(20);
31         //read_and_process_vla(10000000); // Error if stacksize not big enough...
32         printf("======================= not using VLA =======================\n");
33         read_and_process_novla(10);
34         read_and_process_novla(20);
35         read_and_process_novla(10000000);
36         return(0);
37 }