Subject: Re: Use of malloc/free in c-ares

Re: Use of malloc/free in c-ares

From: codemastr <codemstr_at_ptd.net>
Date: 2005-03-08

> Can you write the code that way and it still looks pretty and readable?
Here is what I did in my program. It's not the "prettiest" (macros), but it
works and it's much cleaner than having a million #ifdefs. There are two
macros, DYN_LOCAL, and DYN_FREE. The syntax is:
DYN_LOCAL(data_type, var_name, size_of_array);
DYN_FREE(var_name);

DYN_FREE is defined as free if malloc is being used, otherwise it's defined
as nothing. DYN_LOCAL is defined as follows:
#if defined(HAVE_C99_VARLEN_ARRAY)
#define DYN_LOCAL(type, name, size) type name[size]
#elif defined(HAVE_ALLOCA)
#define DYN_LOCAL(type, name, size) type *name = (size ? alloca(size) :
NULL)
#else
#define DYN_LOCAL(type, name, size) type *name = (size ? malloc(size) :
NULL)
#endif

Basically, it constructs the variable using whichever method is most
efficient. So in the snippet I pasted, we'd simply do:

DYN_LOCAL(char, tmp_buf, strlen(name)+1);
strcpy(tmp_buf, name);
hostent.h_name = tmp_buf;
callback(arg, ARES_SUCCESS, &hostent);
DYN_FREE(tmp_buf);

Of course, due to the way DYN_LOCAL is defined, it needs to be treated as a
variable definition and therefore must be at the beginning of a block. Other
than that though, imho it is a pretty clean solution.

>> I'd guess that there are quite a few places where such mallocs could be
>> replaced by a temporary storage allocation method.
>
> Is it really? If so, we should rather first figure out if this really is
> the case and then check if this really hurts performance in any
> significate way. I have a gut feeling it doesn't...
It may not hurt performance significantly, however, it has to have an
effect. Malloc is not always an efficient function. It could require calls
into the kernel and other stuff that makes it very inefficient. I'm
confident there are multiple locations where the new system can be used
(I've already found at least one more), so it seems worth while to me. I
also know that one of the main criticisms of ares was its use of malloc for
internal storage. So if we can reduce it's usage of it, it might boost its
popularity.

Dominick Meglio

_______________________________________________
http://cool.haxx.se/mailman/listinfo/c-ares
Received on Tue Mar 8 19:16:05 2005