The Linux man page for snprintf (3) shows an example:
#include <stdio.h> #include <stdlib.h> #include <stdarg.h> char * make_message(const char *fmt, ...) { int n; int size = 100; /* Guess we need no more than 100 bytes */ char *p, *np; va_list ap; if ((p = malloc(size)) == NULL) return NULL; while (1) { /* Try to print in the allocated space */ va_start(ap, fmt); n = vsnprintf(p, size, fmt, ap); va_end(ap); /* Check error code */ if (n < 0) return NULL; /* If that worked, return the string */ if (n < size) return p; /* Else try again with more space */ size = n + 1; /* Precisely what is needed */ if ((np = realloc (p, size)) == NULL) { free(p); return NULL; } else { p = np; } } }
After /* check error code */ this should not be:
if (n < 0) { free(p); return NULL; }
to avoid memory leak?
I can't post this because the word-to-code relationship is wrong, so I need to add more text at the end. Please ignore this paragraph as the above is complete and accurate. Hope this is enough for the text to be acceptable.
By the way: I like the last line p = np;
c linux printf manpage
Roobie nuby
source share