d malloc

H. S. Teoh via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Aug 8 09:49:56 PDT 2014


On Fri, Aug 08, 2014 at 04:42:12PM +0000, seany via Digitalmars-d-learn wrote:
> consider this :
> 
> struct S
> {
> /* ... */
> 
> }
> 
> void main()
> {
>    ulong [] u;
> 
>    for(// ...
>    {
>       S s_instance;
>       // fillup .. S.key = value;
>       u ~= cast(ulong)*s_instance;
>    }
> 
> }
> 
> however, the structs are being allocated to the same place. Because,
> Every time the iterator ends an iteration, seemingly, s_instance is
> collected as garbage.

This has nothing to do with the GC. You're storing an address to a local
variable on the stack, which is bad idea because once it goes out of
scope, it will get overwritten by other data (such as subsequent
instances of itself in the loop body).

You need to explicitly allocate the struct on the heap with 'new' if you
want it to survive past the end of the loop body:

	S* s_instance = new S();
	u ~= cast(ulong)s_instance;

Note that as long as you have pointers to the struct, the GC will not
collect it. So you actually don't need to worry about freeing the data
once you're done with it; just set all pointers to it to null, and the
GC will collect it for you.


T

-- 
Why are you blatanly misspelling "blatant"? -- Branden Robinson


More information about the Digitalmars-d-learn mailing list