17

I have a concern about variable-length arrays. When I want to allocate an array dynamically, I'll get null, if it is not possible to allocate enough memory and I can respond to this properly in my program. With a variable length array I don't get this information. What should I do with this?

gruszczy
  • 40,948
  • 31
  • 128
  • 181

1 Answers1

40

You are right that VLA's are basically always unsafe. The only exception is if you ensure that you never make them larger than a size you would feel safe making a fixed-size array, and in that case you might as well just use a fixed-size array. There is one obscure class of recursive algorithms where VLA's could make the difference between being unable to solve the problem (stack overflow) and being able to, but for the most part, I would recommend never using VLA's.

That doesn't mean VLA types are useless, though. While VLA is bad/dangerous, pointer-to-VLA types are extremely useful. They make it possible to have dynamically-allocated (via malloc) multi-dimensional arrays without doing the dimension arithmetic manually, as in:

size_t n;
double (*matrix)[n] = malloc(n * sizeof *matrix);

to get an n-by-n matrix addressable as matrix[i][j].

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
  • 7
    I never really considered using VLA-casts for this. I always thought it'd be set in stone. – Chris Lutz Sep 06 '11 at 22:25
  • 1
    How is that possible that you are allocating memory for `n*n` matrix for a pointer to an array of `n` `double`s? – haccks Jun 05 '14 at 16:38
  • 4
    @haccks: When dynamically allocating an array, you want the pointer type to match the type of the array's elements, since it will point to the first element. (Note that this is the same type the array decays to.) In the case of a two-dimensional array, its elements are one-dimensional arrays of a particular length (here `n`), so you want a pointer to `double[n]`. The call to `malloc` allocates space for `n` such arrays (`sizeof *matrix` gives the size of one such array), so you end up with a pointer to the first element of an array of `n` `double[n]` objects -- a two-dimensional array. – R.. GitHub STOP HELPING ICE Jun 05 '14 at 19:48
  • @R..; Thanks for clarifying. After reading your answer I thought over it and finally got it but forgot to remove the comment :P – haccks Jun 06 '14 at 00:45
  • note: the proper terminology for "VLA types" is *variably modified type* – M.M Sep 30 '14 at 04:40