Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why no variable size array in stack?

Tags:

I don't really understand why I can't have a variable size array on the stack, so something like

foo(int n) {    int a[n]; } 

As I understand the stack(-segment) of part of the data-segment and thus it is not of "constant size".

like image 666
user695652 Avatar asked Oct 18 '11 19:10

user695652


People also ask

Why are variable length arrays bad?

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.

Can you declare an array size with a variable?

size is a variable, and C does not allow you to declare (edit: C99 allows you to declare them, just not initialize them like you are doing) arrays with variable size like that. If you want to create an array whose size is a variable, use malloc or make the size a constant.

Are arrays allocated in the stack?

Unlike Java, C++ arrays can be allocated on the stack. Java arrays are a special type of object, hence they can only be dynamically allocated via "new" and therefore allocated on the heap.

Are variable length arrays allowed in C++?

Variable-length arrays can not be included natively in C++ because they'll require huge changes in the type system.


1 Answers

Variable Length Arrays(VLA) are not allowed in C++ as per the C++ standard.
Many compilers including gcc support them as a compiler extension, but it is important to note that any code that uses such an extension is non portable.

C++ provides std::vector for implementing a similar functionality as VLA.


There was a proposal to introduce Variable Length Arrays in C++11, but eventually was dropped, because it would need large changes to the type system in C++. The benefit of being able to create small arrays on stack without wasting space or calling constructors for not used elements was considered not significant enough for large changes in C++ type system.

like image 65
Alok Save Avatar answered Sep 17 '22 20:09

Alok Save