Subject: Use of malloc/free in c-ares

Use of malloc/free in c-ares

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

I'm still playing around with some IPv6 stuff, and I noticed something... c-
ares uses malloc/free a lot! I am far from an expert on memory management,
but I think the situation can be improved. As an example, let me offer a
snippet from fake_hostent (a function I'm currently adding IPv6 support to):

static int fake_hostent(const char *name, ares_host_callback callback,
                        void *arg)
{
[...]
  struct hostent hostent;
[...]
  hostent.h_name = strdup(name);
[...]
  callback(arg, ARES_SUCCESS, &hostent);
  free(hostent.h_name);
  return 1;
}

Now, is that strdup (essentially a malloc/strcpy) really necessary? In the
C99 world, wouldn't something like:
  char buf[strlen(name)+1];
  strcpy(buf, name);
  hostent.h_name = buf;
be just as effective?

And for the non-C99 world, wouldn't this be a good use for alloca()? What I
mean is, we aren't actually returning the allocated buffer, we are using it
for temporary storage of a buffer of variable length. The C99 variable-length
array definition seems perfect, and alloca() seems like a great alternative
for non-C99 compilers. Both of these methods should be significantly faster
than having to allocate memory on the heap, the C99 method should be near-0
CPU time. I know in my program I implemented a system that does something
similar. If the C99 method is available, it uses that, if not it falls back
to alloca, and if that's not there, then it does malloc. But since gcc
supports the C99 method and MSVC supports alloca (well _alloca), 90+% of the
time, malloc is avoided and hence the library will perform much more
efficiently.

As I said, I'm not an expert when it comes to memory management, but this
seems like a good idea. I'd guess that there are quite a few places where
such mallocs could be replaced by a temporary storage allocation method.

Dominick Meglio

_______________________________________________
http://cool.haxx.se/mailman/listinfo/c-ares
Received on Tue Mar 8 04:56:20 2005