[MPlayer-dev-eng] [PATCH 2/4] String handling audit/cleanup take 2

Rich Felker dalias at aerifal.cx
Thu Mar 8 21:17:57 CET 2007


On Thu, Mar 08, 2007 at 12:17:55PM +0100, Reimar Döffinger wrote:
> Hello,
> On Thu, Mar 08, 2007 at 12:02:11PM +0100, Reimar D?ffinger wrote:
> [...]
> > So, and to be productive I was thinking of something like that (I did
> > not think long about it, so bear with any bugs/stupidity and ignore the
> > stupid names):
> > add a
> > mpsnprintf that behaves like snprintf except that it aborts when the
> > string does not fit
> > BUFPRINTF macro for static arrays that does mpsnprintf(buf, sizeof(buf), ...)
> 
> Forgot: and something similar to asprintf, this should simplify quite a
> bit of code.

OK here's some code..

Should be identical to GNU semantics:

int vasprintf(char **s, const char *fmt, va_list ap)
{
	int len;
	va_list ap2;

	va_copy(ap2, ap);
	len = vsnprintf(NULL, 0, fmt, ap2);
	va_end(ap2);
	if (len >= 0) {
		if (!(*s = malloc((size_t)len+1)))
			return -1;
		vsnprintf(*s, (size_t)len+1, fmt, ap);
	}
	return len;
}

Or the more convenient wrapper:

char *wrap_vasnprintf(const char *fmt, va_list ap)
{
	char *s;
	return vasnprintf(&s, fmt, ap) < 0 ? NULL : s;
}

Feel free to substitute a version which aborts when the malloc fails,
but if you do that then you need to make sure it's not called from
code that's not allowed to abort.. IMO it's better to do the error
return and either signal error or abort in the calling code.

Also perhaps useful:
#ifndef va_copy
#define va_copy(dest,src) (dest)=(src)
#endif

Rich



More information about the MPlayer-dev-eng mailing list