www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Freeing memory allocated at C function

reply Pedro Lacerda <kanvuanza gmail.com> writes:
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?
Mar 22 2012
parent reply =?UTF-8?B?QWxpIMOHZWhyZWxp?= <acehreli yahoo.com> writes:
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
Mar 22 2012
parent Pedro Lacerda <kanvuanza gmail.com> writes:
On Fri, Mar 23, 2012 at 3:43 AM, Ali =C7ehreli <acehreli yahoo.com> wrote:

 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, i=
t
 is undeterministic when the destructor will be called, or will it be call=
ed
 at all!

 Or you can wrap in a struct which has deterministic destruction like in
 C++, when leaving scopes.
The object is long lived, so the class wrapper is the way to go. Thanks
Mar 23 2012