[neomutt-devel] why casting pointer in mutt_mem_free

Yubin Ruan ablacktshirt at gmail.com
Tue Mar 27 10:05:51 CEST 2018


On Tue, Mar 27, 2018 at 07:35:47AM +0000, Pietro Cerutti wrote:
> On Mar 27 18 15:04, Yubin Ruan wrote:
> > In mutt/memory.c, what is point of casting ptr from (void *) to (void **)? Any
> > ancient C technique here?
> > 
> > void mutt_mem_free(void *ptr)
> > {
> >  if (!ptr)
> >    return;
> >  void **p = (void **) ptr;
> >  if (*p)
> >  {
> >    free(*p);
> >    *p = 0;
> >  }
> > }
> 
> Usage would be:
> 
> char *c = mutt_mem_malloc(10);
> mutt_mem_free(&c);
> assert(c == NULL);
> 
> That is, calling mutt_mem_free sets the pointer object pointed-to by the
> argument to NULL. For doing this, mutt_mem_free needs to get passed a
> pointer to the object, which is itself a pointer variable. Hence the &c in
> the invokation.
> 
> Now, any pointer is implicitely convertible to void* as per the C standard,
> but not to void**. This is why the explicit cast inside mutt_mem_free is
> needed to get back the original pointer-to-pointer from the expected pointer
> object.

Very clear ;-) Thanks Pietro.

Yubin


More information about the neomutt-devel mailing list