bug-gnulib
[Top][All Lists]
Advanced

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

Re: gnulib and *printf


From: Eric Blake
Subject: Re: gnulib and *printf
Date: Wed, 07 Oct 2009 19:08:15 -0600
User-agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.23) Gecko/20090812 Thunderbird/2.0.0.23 Mnenhy/0.7.6.666

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

According to Joel E. Denny on 10/7/2009 5:25 PM:
> Hi.
> 
> I have a couple of questions about gnulib's support for the printf family.
> 
> 1. Is the snprintf-posix module helpful in order to use the following 
> portably?
> 
>   length = snprintf (NULL, 0, format, args);
>   str = malloc (length + 1);
>   snprintf (str, length + 1, format, args);

Yes.  But in my opinion, it is even slicker to use either the
xvasprintf{-posix} module, which mallocs for you and calls xalloc_die
automatically on malloc failure:

char *buf = xasprintf (format, args);

or the vasnprintf{-posix} module, which helps manage an existing buffer,
so that you can avoid malloc overhead in the common case of small output:

char buf[100];
size_t len = sizeof (buf);
char *out = asnprintf (buf, &len, format, args);
if (!out)
  handle error
else
  {
    use out
    if (out != buf)
      free (out);
  }

I suppose we could add xvasnprintf, if you want to further avoid error
checking on asnprintf.

> The snprintf man page warns of portability problems for the first snprintf 
> invocation above, but snprintf-posix appears to test only vsnprintf's 
> functionality for this purpose by invoking gl_VSNPRINTF_ZEROSIZE_C99.  Am 
> I misunderstanding the module?  Is it assuming snprintf and vsnprintf will 
> always manage to behave consistently in this respect?

Yes, for every known system, snprintf is just a simple va_arg wrapper that
forwards to vsnprintf, so if the latter has a bug, then the former will as
well.

> 
> 2. Is there any single module that ensures portability of all *printf 
> functions?  Or is it worthwhile to maintain a list of modules trimmed to 
> exactly the functions that are currently used?

At the moment, you have to pull in all the modules one by one.  You can
pull in more than you currently use, if you want to play it safe.  Also,
compiling with -DGNULIB_POSIXCHECK is supposed to help identify places
where you might be missing a module.  Maybe it would be worth an
uber-printf{-posix} module that pulls in all the variants, but I'm
probably not going to write it.

- --
Don't work too hard, make some time for fun as well!

Eric Blake             address@hidden
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (Cygwin)
Comment: Public key at home.comcast.net/~ericblake/eblake.gpg
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iEYEARECAAYFAkrNO38ACgkQ84KuGfSFAYAIGQCbB1GIqrPz83qB4IFR+Afm37zy
iPcAniDxET83NZtVxQOoABFeZ9LSAOsl
=gkth
-----END PGP SIGNATURE-----




reply via email to

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