1

I read that while dynamic memory is allocated on the heap during runtime, static memory is allocated on the stack during compile time since the compiler knows how much memory has to be allocated at compile time.

Consider the following code:

int n;
cin>>n;
int a[n];

How does the compiler possibly know how much memory to allocate for a[] at compile time if its actual size is read during the run only?

Botond
  • 2,640
  • 6
  • 28
  • 44
  • 5
    Most likely an extension variable length arrays are C99 feature but are not allowed in C++, see [this previous question](http://stackoverflow.com/q/19775954/1708801) which explains both `gcc` and `clang` allow this but will warn with `-pedantic` flag. – Shafik Yaghmour Jun 15 '15 at 14:29
  • 3
    The stack and the heap are by no means tied to static and dynamic allocation respectively. It is absolutely possible to allocate memory dynamically on the stack. See the `alloca` function. – Theodoros Chatzigiannakis Jun 15 '15 at 14:37
  • That's an excellent point and it should be mentioned every time dynamic and static allocations are discussed. Is it possible to allocate statically on the heap as well? – Botond Jun 15 '15 at 14:47
  • My understanding is that `static` and global variables may be allocated in memory that is neither *stack* nor *heap*. See `ELF` executable format for more options. – Thomas Matthews Jun 15 '15 at 16:08

1 Answers1

4

You won't be able to compile that, for the exact reason you specified. C++ needs to have a fixed number in there in order for compilation to be performed. If you want to do that, you have to use dynamic allocation.

Lawrence Aiello
  • 4,560
  • 5
  • 21
  • 35