3

I believe that size of the array should be a constant int when you declare it. However, I compiled the following code and it did not get any error. Could you explain about this?

#include <stdio.h>

void function(int);

int main(void){
  int m = 0;
  scanf("%d", &m);
  function(m);
  return 0;
}

void function(int i){
  int array[i];
}

input: 5 output: nothing. but got no error.

Peter Hwang
  • 971
  • 1
  • 12
  • 25
  • 4
    [VLA](http://en.wikipedia.org/wiki/Variable-length_array). – Maroun Oct 02 '13 at 07:14
  • The C standard has evolved on that aspect, and some compilers accepted VLA ([Variable Length Arrays](http://en.wikipedia.org/wiki/Variable-length_array)) as an extension before the standard was defined. See also [Flexible Array Members](http://pic.dhe.ibm.com/infocenter/iseries/v7r1m0/index.jsp?topic=%2Frzarg%2Fflexible.htm) – Basile Starynkevitch Oct 02 '13 at 07:16
  • Thank you. So the required spaces are allocated in run time at the stack? – Peter Hwang Oct 02 '13 at 07:18
  • So it is not unusual to see c structs with last members of the form int ar[] or int ar[0], where memory for these are allocated latter. – fkl Oct 02 '13 at 07:18
  • @user1798211 C does not specify memory organization. Many architectures will place a VLA on the "stack". It could just as well be placed in some other pool of memory. The C VLA construct assures the allocation, deallocation, scope & lifetime of `array[i]`, not its location. – chux - Reinstate Monica Oct 02 '13 at 13:16

2 Answers2

4

Added from C99 a variable-length array (or VLA) is an array data structure of automatic storage duration whose length is determined at run time (instead of at compile time).

VLA works by placing the array in the stack. This makes allocation and access extremely fast, but the stack is usually small (of a few KB), and when the VLA overflows the stack, it's indistinguishable from an infinite recursion.

Sadique
  • 22,572
  • 7
  • 65
  • 91
  • 2
    However, the length is limited to `SIZE_MAX` bytes :) – HAL Oct 02 '13 at 07:17
  • And practically the VLA length is limited to a much lower bound. Typical call stack frames should be a few kilobytes. One megabyte for a single call stack frame is huge on current systems. – Basile Starynkevitch Oct 02 '13 at 07:22
  • @Acme I find no C specification that a VLA resides in the "stack". A VLA may exist on the "stack" as you suggest, it may exist in the same memory pool as malloc/free. Its speed and location are platform (and maybe runtime) dependent. – chux - Reinstate Monica Oct 02 '13 at 13:22
1

Why should the program return a error ? what where you expecting ?Check for VLA in C.

Reference_to_VLA

vkulkarni
  • 849
  • 1
  • 8
  • 12