-1

Dynamic memory allocation in C/C++ happens through malloc and the static memory allocation ex: int a[3]; its allocated after the code is executed.

But this code int x[y+1]; only can happen after a value is attributed to y and this happens in execution time, so its static, dynamic or both? does the compiler insert a malloc in the machine code automatically?

Ollegn
  • 2,294
  • 2
  • 16
  • 22
  • 2
    Side note: `int x[y+1]` is not valid C++ (although most compilers support it), it is valid only in C. – vsoftco Apr 24 '15 at 02:20

2 Answers2

4

It is a Variable Length Array (VLA). Wikipedia: http://en.wikipedia.org/wiki/Variable-length_array

Technically, it is not legal in C++, but compilers often support it as an extension, but generate warnings when they are turned on. See Why aren't variable-length arrays part of the C++ standard?

It is legal in C.

Community
  • 1
  • 1
Arun
  • 19,750
  • 10
  • 51
  • 60
  • Pay particular attention to the footnote regarding its inclusion in C99 and subsequent relegation to a conditional feature that is not required to be supported (C11 Standard, Section 6.7.6.2 - 4) E.g., see latest free draft: [**Programming Languages - C, International Standard (Committee Draft N1570, April 12, 2011)**](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf) – David C. Rankin Apr 24 '15 at 03:04
0

int[] is on the stack, while malloc'd or new'd things are on the heap.

VERY basically int[] gets allocated automatically when it is reached (where y is already known) and gets dropped when it gets out of scope. It is not everything already allocated at startup.

There are no hidden malloc calls or stuff, that is just how the stack memory works.

(I hope for an answer from someone who actually knows C/C++)

Felk
  • 7,720
  • 2
  • 35
  • 65