Y'a des trucs qui reviennent dans beaucoup de mes codes, pour la manipulation de string en C. Notement un qui permet de faire un sprintf de manière sure :
/* Allocate a string large enough and sprintf in it. * Halt program on error. */ int xasprintf (char **strp, const char *fmt, ...) { assert (strp); char *text = NULL; ssize_t size = 64; va_list ap; while (1) { int nsize; text = xrealloc (text, size); /* Try to print in the allocated space. */ va_start (ap, fmt); nsize = vsnprintf (text, size, fmt, ap); va_end (ap); /* Did it worked ? */ if (-1 < nsize && nsize < size) break; /* Try again with more space. */ if (nsize > -1) size = nsize + 1; // C99, nsize == precisely what is needed else size *= 2; // windows, plan9, ... } *strp = text; return strlen (text); }
Il est basé sur un wrapper à realloc() qui arrête le programe en cas d'échec d'allocation.
/* wrapper to realloc aborting on error */ void * xrealloc (void *ptr, size_t size) { void *nptr = realloc (ptr, size); if (!nptr) error (1, errno, "realloc() failed"); return nptr; }