Remove an unnecessary allocation.
[oweals/opkg-lede.git] / libopkg / sprintf_alloc.c
1 /* sprintf_alloc.c -- like sprintf with memory allocation
2
3    Copyright (C) 2010 Ubiq Technologies <graham.gower@gmail.com>
4
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 2, or (at your option)
8    any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14 */
15
16 #include <stdarg.h>
17
18 #include "sprintf_alloc.h"
19 #include "libbb/libbb.h"
20
21 void
22 sprintf_alloc(char **str, const char *fmt, ...)
23 {
24         va_list ap;
25         int n;
26         unsigned int size = 0;
27
28         *str = NULL;
29
30         for (;;) {
31                 va_start(ap, fmt);
32                 n = vsnprintf (*str, size, fmt, ap);
33                 va_end(ap);
34
35                 if (n < 0) {
36                         fprintf(stderr, "%s: encountered an output or encoding"
37                                         " error during vsnprintf.\n",
38                                         __FUNCTION__);
39                         exit(EXIT_FAILURE);
40                 }
41
42                 if (n < size)
43                         break;
44
45                 /* Truncated, try again with more space. */
46                 size = n+1;
47                 *str = xrealloc(*str, size);
48         }
49 }