On 04/09/2011 10:29 AM, Andrew Dunbar wrote:
I've got a little program to index dump files that supports Windows and Linux but it doesn't compile on the Toolserver with either cc or gcc due to the lack of the function vasprintf(). It's a GNU extension so I'm surprised it didn't work even with gcc.
Why doesn't the Toolserver gcc have it, and does anybody know of a workaround?
vasprintf() is a version of vsprintf() which writes to a memory buffer of just the right size that it allocates and which the caller must call free() on when done.
You could try writing your own. Off the top of my head (untested):
char *vasprintf (const char *format, va_list ap) { int len; char *buf; len = vsnprintf(NULL, 0, format, ap); /* get needed size */ if (len < 0) return NULL; buf = malloc(len + 1); /* reserve 1 byte for trailing \0 */ if (!len) return NULL; if (vsnprintf(buf, len + 1, format, ap) == len) return buf; free(buf); /* something went wrong in second vsnprintf() */ return NULL; }
I think the vsnprintf(NULL, 0, ...) trick should work, although I haven't tried it. If it complains about the NULL, just use some valid dummy pointer instead. You could probably trade some memory for speed in some cases by guessing and allocating some reasonable initial size for the buffer before the first vsnprintf() call and extending it only if the first guess wasn't long enough.