bug-gnulib
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [PATCH] snprintf: port snprintf (NULL, 0, ... ) to Solaris 8 and 9


From: Jim Meyering
Subject: Re: [PATCH] snprintf: port snprintf (NULL, 0, ... ) to Solaris 8 and 9
Date: Wed, 22 Dec 2010 23:11:11 +0100

Bruno Haible wrote:
> Eric Blake wrote:
>> one _very_ common use of snprintf is to call it with size 0 to see
>> how much to allocate, then allocate and call again.
>
> Why do people do this? It appears to be slower than just calling
> asprintf, because it has to parse the format string and produce
> the expansion twice.

Hi Bruno,

One reason I would want to use the first approach is to insert a guard
after the first snprintf call that will ensure the second does not
attempt to allocate 2GiB of heap and then write into it.  Of course, for
that to be useful, snprintf (NULL, 0, ...  would have to be implemented
in such a way (unlike glibc's) that it does not allocate space for the
entire result.

> ====================== foo.c ==========================
> #define _GNU_SOURCE 1
> #include <stdio.h>
> #include <stdlib.h>
>
> int main (int argc, char *argv[])
> {
>   int REPEAT = atoi (argv[1]);
>   int ALGO = atoi (argv[2]);
>   const char *fmt = "%d";
>   int arg1 = 12345;
>
>   if (ALGO == 0)
>     {
>       int repeat;
>
>       for (repeat = REPEAT; repeat > 0; repeat--)
>         {
>           int len = snprintf (NULL, 0, fmt, arg1);
>           char *mem = malloc (len + 1);
>           snprintf (mem, len + 1, fmt, arg1);
>           free (mem);
>         }
>     }
>   else
>     {
>       int repeat;
>
>       for (repeat = REPEAT; repeat > 0; repeat--)
>         {
>           char *mem;
>           if (asprintf (&mem, fmt, arg1) < 0)
>             abort ();
>           free (mem);
>         }
>     }
>
>   return 0;
> }



reply via email to

[Prev in Thread] Current Thread [Next in Thread]