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

Re: Use of malloc/free in c-ares

From: Daniel Stenberg <daniel_at_haxx.se>
Date: 2005-03-08

On Tue, 8 Mar 2005 codemstr@ptd.net wrote:

> 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?

Yes, it would work and be a lot faster. But we cannot assume C99 since we want
greater portability than so.

> And for the non-C99 world, wouldn't this be a good use for alloca()?

Sure, but alloca() is not a standard function so there will be systems with
C89 compilers that lack alloca()...

> 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.

Can you write the code that way and it still looks pretty and readable?

> 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.

Another alternative is to simply allocate space for it on the stack for the
worst case:

  char name[MAX_NAME];

... unless it can be very big.

> 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...

-- 
          -=- Daniel Stenberg -=- http://daniel.haxx.se -=-
   ech`echo xiun|tr nu oc|sed 'sx\([sx]\)\([xoi]\)xo un\2\1 is xg'`ol
_______________________________________________
http://cool.haxx.se/mailman/listinfo/c-ares
Received on Tue Mar 8 14:26:54 2005