Freeing memory allocated at C function

Ali Çehreli acehreli at yahoo.com
Thu Mar 22 23:43:28 PDT 2012


On 03/22/2012 11:27 PM, Pedro Lacerda wrote:
 > I'm using some C functions like these:
 >
 >      char *str = allocateNewString();
 >
 > And this:
 >
 >      Object *obj = constructObject();
 >      // etc
 >      freeObject(obj);
 >
 >
 > Do I need to free the memory in both cases? Can I someway register 
them on
 > GC?
 >

You can register on GC if you wrap the resources in a class. Then the 
class object's destructor would call the clean up code. The problem is, 
it is undeterministic when the destructor will be called, or will it be 
called at all!

Or you can wrap in a struct which has deterministic destruction like in 
C++, when leaving scopes.

A better thing to do in this case is to use the scope() statement. 
Depending of when you want the cleanup to happen:

- scope(success): if the scope is being exited successfully

- scope(failure): if the scope is being exited with an exception

- scope(exit): when exiting the scope regardless

For example, if you want the cleanup only if there is an exception:

int allocate()
{
     return 42;
}

void deallocate(int)
{}

void foo()
{
     int resource = allocate();
     scope(failure) deallocate(resource);

     // ... an exception may be thrown here ...
}

void main()
{
     foo();
}

Ali



More information about the Digitalmars-d-learn mailing list