Managing malloced memory

H. S. Teoh hsteoh at
Wed Oct 6 18:53:11 UTC 2021

On Wed, Oct 06, 2021 at 06:06:38PM +0000, anon via Digitalmars-d-learn wrote:
> I interface to a C library that gives me a malloced object. How can I manage
> that pointer so that it gets freed automatically.
> What I've thought of so far:
> * struct wrapped in automem/ refcounted: The struct still leaves
> original scope and calls the destructor

Why is it a problem that it calls the dtor?  I thought the whole point
of refcounting is for the dtor to decrement the refcount, and free the
malloc'd object only when the refcount has actually reached 0.

You do have to be careful about copy ctors, assignment operators, and
such, though, to make sure the refcount stays consistent throughout. And
the refcount should probably be on the heap somewhere (either GC heap or
part of the malloc'd object); you would not want a struct's by-value
semantics to make another copy of the refcount and end up freeing the C
object more than once.


Life is unfair. Ask too much from it, and it may decide you don't deserve what you have now either.

More information about the Digitalmars-d-learn mailing list