Stack or heap? What's that?
Stewart Gordon
smjg_1998 at yahoo.com
Sat Jan 13 09:08:35 PST 2007
orgoton wrote:
> One difference between C and D is that data is allocated on the heap instead
> of the stack or something like that.
Not much like that, actually.
Variables of primitive, struct, union and static array types are
allocated on the stack.
Dynamic arrays and class objects are allocated on the heap. Of course,
if such types are declared as local variables, then references to this
data on the heap will be allocated on the stack.
> What does that mean?
<snip>
A stack is a last in first out (LIFO) buffer. _The_ stack is the LIFO
buffer that keeps track of the current nesting of function calls and the
values of local variables.
The heap is an area of memory set aside for dynamic allocation. In C++,
the new and delete keywords are used to allocate and deallocate memory
on the heap. In D, the following actions allocate memory on the heap:
- creating a new object or array using new
- setting the .length of a dynamic array, if it hasn't already been
allocated or needs to grow and there isn't room for it to grow in place
- concatenating arrays using ~= under the same conditions
- concatenating arrays using ~
- calling .dup on an array
and the garbage collector deallocates memory, so normally you don't need
to worry about memory management.
Usually, the only time you need to worry about whether something's on
the heap or the stack is when returning from a function. A common
newbie error seems to be to do something like
int[] returnAnArray() {
int[10] result;
result[] = 42;
return result;
}
which won't work because you're returning a reference to data held on
the stack, and this reference will be invalid once the function has
returned. For it to work, you'd have to cause the array to be on the
heap by doing either
int[] result = new int[10];
or
int[] result;
result.length = 10;
or return a copy of the array instead:
return result.dup;
Of course, it's OK to do something like
int returnAnInt() {
int result = 69;
return result;
}
since an int is returned by value - but usually you wouldn't declare a
result variable like this unless you were doing something more involved.
HTH
Stewart.
More information about the Digitalmars-d
mailing list