vasprintf and asprintf on Solaris 10

By Alasdair Lumsden on 19 Jul 2011

Update: Martin in the comments suggested using the vasprintf definition in the OpenSolaris source.

Vasprintf and asprintf on Solaris 10

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/

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 – 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)
                                *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);
        return size;

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.