0
|
1 #include "dmlib.h"
|
|
2 #include <stdarg.h>
|
|
3
|
|
4 /* strdup with a NULL check
|
|
5 */
|
|
6 char *dm_strdup(const char *s)
|
|
7 {
|
|
8 char *res;
|
|
9 if (s == NULL)
|
|
10 return NULL;
|
|
11
|
|
12 if ((res = dmMalloc(strlen(s) + 1)) == NULL)
|
|
13 return NULL;
|
|
14
|
|
15 strcpy(res, s);
|
|
16 return res;
|
|
17 }
|
|
18
|
|
19
|
|
20 /* Simulate a sprintf() that allocates memory
|
|
21 */
|
|
22 char *dm_strdup_vprintf(const char *fmt, va_list args)
|
|
23 {
|
|
24 int size = 64;
|
|
25 char *buf;
|
|
26
|
|
27 if ((buf = dmMalloc(size)) == NULL)
|
|
28 return NULL;
|
|
29
|
|
30 while (1)
|
|
31 {
|
|
32 int n;
|
|
33 va_list ap;
|
|
34 va_copy(ap, args);
|
|
35 n = vsnprintf(buf, size, fmt, ap);
|
|
36 va_end(ap);
|
|
37
|
|
38 if (n > -1 && n < size)
|
|
39 return buf;
|
|
40 if (n > -1)
|
|
41 size = n + 1;
|
|
42 else
|
|
43 size *= 2;
|
|
44
|
|
45 if ((buf = dmRealloc(buf, size)) == NULL)
|
|
46 return NULL;
|
|
47 }
|
|
48 }
|
|
49
|
|
50
|
|
51 char *dm_strdup_printf(const char *fmt, ...)
|
|
52 {
|
|
53 char *res;
|
|
54 va_list ap;
|
|
55
|
|
56 va_start(ap, fmt);
|
|
57 res = dm_strdup_vprintf(fmt, ap);
|
|
58 va_end(ap);
|
|
59
|
|
60 return res;
|
|
61 }
|