Wireshark-dev: Re: [Wireshark-dev] [PATCH] Re: Freeing memory of se_alloc'ated object

From: Jakub Zawadzki <darkjames-ws@xxxxxxxxxxxx>
Date: Tue, 3 May 2011 16:18:42 +0200
On Tue, May 03, 2011 at 12:59:48AM +0400, Max wrote:
> > About API I'd prefer smth like: se_register_gc_dtor(void *ptr, emem_dtor_cb dtor)
> > which would register already allocated ptr.
> >
> > (+) It'd work with any se_* allocated memory.
> > (+) you can register it any time (not only at allocation)
> > (-) you should check if ptr is valid pointer (se_verify_pointer())
> 
> Can you provide a usecase for such an API? 

I *REALLY* want to have one function for it, instead of zillions.

But oh-well I can give examples of it (probably it won't convience you)

<code>
struct foo {
  FILE *f;
  struct bar *bar;
};

void foo_cleanup(struct foo *foo) {
  fclose(foo->f);
  bar_deinit(foo->bar);
}

struct foo *foo = se_alloc(sizeof(struct foo));
if (!(f->f = fopen("file.txt", "r")))
  return;
if (!(f->bar = bar_init())) {
  fclose(f->f);
  return;
}
se_register_gc_dtor(foo, foo_cleanup);
</code>

In you case you need to: 
  foo->f = NULL;
  foo->bar = NULL;
just after se_alloc(), and you need to check for NULLs inside foo_dtor().

(and please don't mention se_alloc0() as possible solution. 
 Some functions returns -1 when error (open, socket, mmap, iconv), and 0 is valid resource)


Another example is when you store se_allocated pointer in some not-se_allocated structure (or global variable),
and you want to NULL pointer after being freed (or do other things).


Btw. Probably you have seen it, but gcrypt have got API to change allocation functions [1]

[1] http://www.gnupg.org/documentation/manuals/gcrypt/Allocation-handler.html#Allocation-handler