Re: Heap vs Stack allocations

From: E. Robert Tisdale (E.Robert.Tisdale_at_jpl.nasa.gov)
Date: 01/23/04


Date: Thu, 22 Jan 2004 16:27:11 -0800

MSG wrote:

> void f1(int n) { vector<int> x(n); /* C++ */ }
>
> void f2(int n) { int x[n]; /* C99 only */ }
>
> void f3(int n) { int* x = new int[n]; /* C++ */ delete [] x; }
>
> void f4(int n) { int* x = (int*)malloc(n*sizeof(int));
> /*...*/ free(x); }
>
> In all of these cases, it makes sense for the compiler to allocate x
> on the stack instead of the heap.

Why?

> However, AFAIK, only in case of f2, the compiler is required to do so.
> Without learning assembly, is there any see
> how a particular compiler handles each of these cases?

Yes.

Storage for array x is allocated from the free store (the "heap")
in all cases except f2.
Automatic storage is allocated (from the stack) in f2 for array x
if you use a C99 compliant C compiler or a C or C++ compiler
that supports variable size arrays as an extension to C89 or C++.

A new C++ standard has been drafted
but I don't think that it specifies support for variable size arrays ...
yet.