digitalmars.D.learn - Freeing memory allocated at C function
- Pedro Lacerda (8/8) Mar 22 2012 I'm using some C functions like these:
- =?UTF-8?B?QWxpIMOHZWhyZWxp?= (31/39) Mar 22 2012 You can register on GC if you wrap the resources in a class. Then the
- Pedro Lacerda (5/11) Mar 23 2012 ed
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
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 registerthem onGC?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
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=tis undeterministic when the destructor will be called, or will it be call=edat 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