On 09/20/2016 05:49 PM, Kyrill Tkachov wrote:

> Ok, I'm proposing a new function defined in system.h
> (though I'm open to suggestions for other location).
> It would be something like:
> 
> static inline int ATTRIBUTE_PRINTF_3
> gcc_snprintf (char *str, size_t size, const char *format, ...)
> {
>   va_list ap;
>   va_start(ap, format);
>   size_t res = vsnprintf (str, size, format, ap);
>   va_end (ap);
>   /* vsnprintf returns >= size if input was truncated.  */
>   gcc_assert (res < size);
>   return res;
> }
> 
> Would that be acceptable?

gdb has had exactly that for eons:

int
xsnprintf (char *str, size_t size, const char *format, ...)
{
  va_list args;
  int ret;

  va_start (args, format);
  ret = vsnprintf (str, size, format, args);
  gdb_assert (ret < size);
  va_end (args);

  return ret;
}

Maybe reuse the same name?  It follows the naming scheme of
xmalloc, etc., with x meaning it never fails.

Even better would be to put this in libiberty.

And perhaps even better would be to get rid of the hardcoded
buffer sizes and use libiberty's existing xasprintf instead.

Reply via email to