vasprintf and asprintf on Solaris 10
July 19th, 2011
Update: Martin in the comments suggested using the vasprintf definition in the OpenSolaris source.
If you get errors such as this on Solaris 10, it’s due to a lack of modern helpful string functions (which thankfully were added to OpenSolaris, so no problem here on OpenIndiana):
Undefined first referenced symbol in file asprintf ../../bin/gcc/libgpac.so
There’s quite a nice implementation (no idea how safe it is to use, but at least the program now compiles!) over at Stack Overflow – http://stackoverflow.com/questions/4899221/substitute-or-workaround-for-asprintf-on-aix. Take the latter one, by Jonathan Leffler.
You can drop it in like so:
#if (defined (__SVR4) && defined (__sun))
int vasprintf(char **ret, const char *format, va_list args)
{
va_list copy;
va_copy(copy, args);
/* Make sure it is determinate, despite manuals indicating otherwise */
*ret = 0;
int count = vsnprintf(NULL, 0, format, args);
if (count >= 0) {
char* buffer = malloc(count + 1);
if (buffer != NULL) {
count = vsnprintf(buffer, count + 1, format, copy);
if (count < 0)
free(buffer);
else
*ret = buffer;
}
}
va_end(args); // Each va_start() or va_copy() needs a va_end()
return count;
}
int asprintf(char **strp, const char *fmt, ...)
{
s32 size;
va_list args;
va_start(args, fmt);
size = vasprintf(strp, fmt, args);
va_end(args);
return size;
}
#endif
Since the code I'm compiling will not be facing the internet and only run by trusted users, I'm not too worried about how buffer overflow safe this code is. If you are concerned about that, you might want to take a look at gnulib, which has a nice properly portable version, although it's a lot bigger.
Entry Filed under: Solaris

2 Comments Add your own
1. Martin | January 28th, 2012 at 9:45 am
There is also a version in OpenSolaris which might be (a) more battle-tested and (b) closer to what we find in Solaris 11 (which has both asprintf(3C) and vasprintf(3C).
http://src.opensolaris.org/source/xref/onnv/onnv-gate/usr/src/lib/libc/port/print/asprintf.c
2. Alasdair | February 1st, 2012 at 1:46 pm
Thanks Martin.
In case that link stops working, there’s a mirror here:
http://hg.openindiana.org/upstream/oracle/onnv-gate/file/b23a4dab3d50/usr/src/lib/libc/port/print/asprintf.c
Leave a Comment
Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
Trackback this post | Subscribe to the comments via RSS Feed