Newbie questions on memory allocation

Simen kjaeraas simen.kjaras at gmail.com
Sat Jul 24 09:41:32 PDT 2010


Deokjae Lee <asitdepends at gmail.com> wrote:

> Hi there, I have some questions on the following code.
>
> import std.stdio;
>
> struct S {
> 	int x;
> }
>
> void main() {
> 	int[3] a = new int[3];//A
> 	S* b = new S();//B
> 	delete b;//C
> }
>
> What's the meaning of the line A?

Create a static array on the stack, and initialize it with these values
I just got off the heap.


> Is the array allocated on heap? or stack?

a is allocated on the stack. (new int[3]) is allocated on the heap. (and
is no longer referenced, thus will be collected on the next GC cycle.)


> Is it dynamic or static?

a is static, (new int[3]) is dynamic.


> I think the line B is not a good style in D, but anyway I have a  
> question.
> Does the garbage collector concern the object constructed at line B?

Yes. If you want to allocate stuff that the GC is not to know about, you
need to use std.c.stdlib.malloc.


> Is the line C safe?

I'd say no, but the compiler seems to disagree with me. Delete is
however scheduled for deprecation, so shouldn't be used. (instead, use
clear, which clears the state of the object, and collects it on the
next GC cycle.)

-- 
Simen


More information about the Digitalmars-d-learn mailing list