[Top] [All Lists]

Re: [Nmh-workers] GCC 8 pre-releases have escaped...

2018-02-07 14:34:18
Hi Ken,

Yes, I like asprintf(), but it's not POSIX.  snprintf(NULL, 0, fmt,
...) is POSIX and returns the strlen() of what would have been
written, allowing a second call to do the work, again, for real this

A quick glance suggests to me that even while asprintf() is not part
of POSIX, it is on *BSD systems, newer versions of MacOS X, and is in
glibc.  That sounds like pretty good coverage to me.

True, but it's often not the function we want as, you say, it allocates
afresh each time.

I'd personally be willing to live with the inefficiency of a simple
{v}asprintf() implementation that just called {v}snprintf() with a
size of 0 to get the real size and then called it again with a
correctly-allocated buffer.

Yes, that would be a way to implement asprintf() where it was missing.

We could avoid the double effort on most occasions by tracking the
size of the existing allocation and only realloc() when it's not big
enough.  vsnprintf(3) exists so our function can pass on the va_list
to it.

My reading of asprintf() is that it always allocates a new buffer,
even if the pointer you pass in is already allocated.

And that's bad when you're in a loop wanting to snprintf() to a local
char[] you hope is big enough, use the result, and trample it on the
next iteration.  asprintf() adds N×(malloc+free).  What I suggested is a
few realloc()s as the previous one is occasionally found lacking.  If
current size is 256 and 300 is needed then 512 is claimed.

Cheers, Ralph.


<Prev in Thread] Current Thread [Next in Thread>