#include #include #include static void vsnprintf_test(char **str, size_t *alloc_len, size_t *offset, const char *fmt, ...) { #if defined(__hpux) //#define INITIAL_ALLOC_LEN 128 //#define INITIAL_ALLOC_LEN 1 #define INITIAL_ALLOC_LEN 20 int avail_len, written_len = 0; va_list args; if (NULL == *str) { *alloc_len = INITIAL_ALLOC_LEN; printf("Allocating initial %d bytes\n", (int)*alloc_len); *str = (char *)malloc(*alloc_len); *offset = 0; } while (1) { avail_len = *alloc_len - *offset; va_start(args, fmt); written_len = vsnprintf(*str + *offset, avail_len, fmt, args); printf("written_len = %d\n", written_len); va_end(args); if (0 <= written_len) break; if (-1 == written_len) { *alloc_len *= 2; printf("Reallocating to %d bytes\n", (int)*alloc_len); *str = (char *)realloc(*str, *alloc_len); continue; } printf("written_len = %d exiting...\n", written_len); exit(1); } *offset += written_len; #undef INITIAL_ALLOC_LEN #endif } int main(void) { char *msg = NULL; size_t msg_alloc = 0, msg_offset = 0; vsnprintf_test(&msg, &msg_alloc, &msg_offset, "%s", "ABCDEFGHIJ0123456789"); printf("%s\n", msg); free(msg); }