]> eyrie.org Git - kerberos/krb5-strength.git/blob - portable/asprintf.c
0093070abbba0830bf620a4a76a0f1d271188237
[kerberos/krb5-strength.git] / portable / asprintf.c
1 /*
2  * Replacement for a missing asprintf and vasprintf.
3  *
4  * Provides the same functionality as the standard GNU library routines
5  * asprintf and vasprintf for those platforms that don't have them.
6  *
7  * The canonical version of this file is maintained in the rra-c-util package,
8  * which can be found at <http://www.eyrie.org/~eagle/software/rra-c-util/>.
9  *
10  * Written by Russ Allbery <rra@stanford.edu>
11  *
12  * The authors hereby relinquish any claim to any copyright that they may have
13  * in this work, whether granted under contract or by operation of law or
14  * international treaty, and hereby commit to the public, at large, that they
15  * shall not, at any time in the future, seek to enforce any copyright in this
16  * work against any person or entity, or prevent any person or entity from
17  * copying, publishing, distributing or creating derivative works of this
18  * work.
19  */
20
21 #include <config.h>
22 #include <portable/system.h>
23
24 /*
25  * If we're running the test suite, rename the functions to avoid conflicts
26  * with the system versions.
27  */
28 #if TESTING
29 # define asprintf test_asprintf
30 # define vasprintf test_vasprintf
31 int test_asprintf(char **, const char *, ...)
32     __attribute__((__format__(printf, 2, 3)));
33 int test_vasprintf(char **, const char *, va_list);
34 #endif
35
36 int
37 asprintf(char **strp, const char *fmt, ...)
38 {
39     va_list args;
40     int status;
41
42     va_start(args, fmt);
43     status = vasprintf(strp, fmt, args);
44     va_end(args);
45     return status;
46 }
47
48 int
49 vasprintf(char **strp, const char *fmt, va_list args)
50 {
51     va_list args_copy;
52     int status, needed;
53
54     va_copy(args_copy, args);
55     needed = vsnprintf(NULL, 0, fmt, args_copy);
56     va_end(args_copy);
57     if (needed < 0) {
58         *strp = NULL;
59         return needed;
60     }
61     *strp = malloc(needed + 1);
62     if (*strp == NULL)
63         return -1;
64     status = vsnprintf(*strp, needed + 1, fmt, args);
65     if (status >= 0)
66         return status;
67     else {
68         free(*strp);
69         *strp = NULL;
70         return status;
71     }
72 }