Is it's correct to say that ALL types that can grow are place on heap?

Ali Çehreli acehreli at yahoo.com
Sat Sep 8 22:51:17 UTC 2018


On 09/08/2018 02:19 AM, Suliman wrote:
 > Is it's correct to say that ALL types that can grow are place on heap
 > and types that not growing (int, char, pointer) are place on stack?

The question is not that simple. :)

First, there is also the area used for objects that are static and 
object that are defined at module scope. That is different from both the 
call stack and the heap. Let's ignore them...

There are automatic objects like local variables inside a function and 
function parameters. They normally live on the stack. (However, the 
compiler may pass some parameters in CPU registers without allocating 
any memory at all.)

As you say, whenever memory is dynamic in nature e.g. we don't know the 
size before hand, the memory is normally allocated from the heap. 
However, heap can be used for allocating even an int:

import std.stdio;

void main() {
     auto p = new int(42);
     writeln(p);
     writeln(*p);
}

Although the memory used for the elements of a dynamic array is on the 
heap, the slice itself is usually on the stack:

import std.stdio;

void main() {
     auto arr = [ 42 ];
     writeln("Local slice variable is at       ", &arr);     // stack
     writeln("The elements of the array are at ", arr.ptr);  // heap
}

Then there are member variables of a user-defined type: Obviously, those 
variables are wherever the actual object lives.

 > Or there is some exceptions?
 >
 > Is there any tools that can visualize place of data in memory?

I think there are some debuggers that visualize data like that but I 
don't have experience with those.

Ali



More information about the Digitalmars-d-learn mailing list