Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to use variable-length arrays?

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?

like image 686
gruszczy Avatar asked Sep 06 '11 21:09

gruszczy


People also ask

Why are variable length arrays bad in C?

The biggest problem is that one can not even check for failure as they could with the slightly more verbose malloc'd memory. Assumptions in the size of an array could be broken two years after writing perfectly legal C using VLAs, leading to possibly very difficult to find issues in the code.

Is VLA allowed in C?

In C, the VLA is said to have a variably modified type that depends on a value (see Dependent type). The main purpose of VLAs is to simplify programming of numerical algorithms.

Can array length be a variable?

A variable length array, which is a C99 feature, is an array of automatic storage duration whose length is determined at run time. If the size of the array is indicated by * instead of an expression, the variable length array is considered to be of unspecified size.

What is the purpose of length variable in array?

The length variable in an array returns the length of an array i.e. a number of elements stored in an array. Once arrays are initialized, its length cannot be changed, so the length variable can directly be used to get the length of an array. The length variable is used only for an array.


1 Answers

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].

like image 107
R.. GitHub STOP HELPING ICE Avatar answered Sep 19 '22 09:09

R.. GitHub STOP HELPING ICE