vasprintf and asprintf on Solaris 10

0 Flares 0 Flares ×
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):

1
2
3
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#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.

0 Flares Twitter 0 Facebook 0 Google+ 0 Reddit 0 LinkedIn 0 StumbleUpon 0 Email -- 0 Flares ×

Tags: , , , , , , , , , , , , ,

2 Responses to “vasprintf and asprintf on Solaris 10”

  1. Martin says:

    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

Leave a Reply

Back to top