-4

In general, should I use variable length arrays or malloc? In my specific case I am processing files of very short to very large sizes. Also if I compile on version MacOS 10.15, and then run on 10.13, it seems VLA's won't work. Malloc is more likely to work. What should I use?

2
  • Remember that VLAs are allocated on the stack, and won't persist after the allocating functions returns. If you need dynamic lifetime, you need dynamic allocation through malloc.
    – Alexander
    Jun 24, 2020 at 2:44
  • I made a long answer about that on SO that you might find useful stackoverflow.com/a/58163652/6699433
    – klutt
    Jul 7, 2020 at 20:16

2 Answers 2

0

Malloc vs variable length array?

When to use malloc()

  • Array size might be large.

  • Validation of successful availability is needed. Check against NULL possible with malloc(), not so with VLA.

  • Code might compile in C11 (or later) without VLA support or before C99. Conditional code involves checking __STDC__, __STDC_VERSION__, __STDC_NO_VLA__ for VLA availability.

When to use variable length array

  • A useful place is not in making the VLA itself, but used in a function parameter.

data below requires VLA ability. Although the row in data[row][col] does not affect the type, the col simplifies later code in accessing data[][].

int foo(size_t row, size_t col, int data[row][col]) {
  ...
  bar(data[r][c]);
} 

See also What's the point of VLA anyway?

  • In forming a type to allocate.

Like above, a VLA is not formed, but a pointer to a VLA is used.

int sz1 = rand()%100 + 1;
int sz2 = rand()%100 + 1;
int (*abc)[sz1][sz2] = malloc(sizeof *abc);
  • When there is tight size control of possible (small) array sizes.

    int pixel_primaries;
    if (rgb) pixel_primaries = 3;
    else if (rgba) pixel_primaries = 4;
    else pixel_primaries = 1; // monochrome
    
    int pixel[pixel_primaries];
    foo_manipulate_pixel(pixel_primaries, pixel);
    
  • Quick dirty code

      int sz;
      scanf("%d", &n);
      assert(sz > 0 && sz < 100);
      int vla[n];
      ...
    

What should I use?

Follow your group's coding standards. VLA or not tends to be a holy war.

For me, I find VLAs useful in multi-dimensions helper functions as above.

0
1

If you found a case where VLAs don’t work, I’d say that is a pretty good reason not to use them. The real problem is likely that stack space is limited (megabytes) while malloc is much less limited (gigabytes).

Never use VLAs if you don’t have a low maximum size for the array. So not for “files of very large sizes”.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.