Variable Length vs Malloc-ed arrays
According to c99 standard, we can write the following code and it's totally legal
int x;
scanf("%d",&x);
int ar[x];
My question is, if I can allocate an array like this, why would I ever need malloc to allocate variable size arrays again?
Also, could you please explain how does the var开发者_开发问答iable length arrays allocation happens? Deep inside, does it call malloc to allocate the array or what?
Two reasons spring to my mind:
- Arrays that live beyond this stack frame.
- Arrays that are bigger than the stack.
Variable length array allocation (or any array declaration actually) is done on the stack (assuming GCC compiler). Malloc assigns memory from the heap.
Two advantages to heap vs. stack: 1. Stack is much smaller. There is a decent chance that your variable-size array could cause your stack to overflow. 2. Items allocated on the stack don't survive after the function they were declared in returns.
In the C11 standard, variable length arrays became "optional" which I take to mean "implementation defined" and as such they are no longer portable.
This is shown in
6.7.6.2 Array declarators section 4
Variable length arrays are a conditional feature that implementations need not support.
and
6.10.8.3 Conditional feature macros section 1
__STDC_NO_VLA__
The integer constant 1, intended to indicate that the implementation does not support variable length arrays or variably modified types.
Some advantages of using malloc
over the VLA are:
- The implementation of
malloc
usually obtains memory from the heap which in most C implememtations is a bigger resource than the stack. However neither heap nor stack are mentioned in the C standard, but they are common ways to implement global and local memory. - Memory obtained from
malloc
can be increased or reduced byrealloc
but it is not possible with a VLA. - Memory obtained from
malloc
can be passed around the program untilfree
d, with pointers, but the VLA can only be used in a hierarchy of functions. The VLA becomes dead after the function in which it is defined returns, because it goes out of scope.
精彩评论