]> eyrie.org Git - kerberos/krb5-strength.git/blob - portable/asprintf.c
Add license statement to autogen
[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 <eagle@eyrie.org>
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 #include <errno.h>
25
26 /*
27  * If we're running the test suite, rename the functions to avoid conflicts
28  * with the system versions.
29  */
30 #if TESTING
31 # define asprintf test_asprintf
32 # define vasprintf test_vasprintf
33 int test_asprintf(char **, const char *, ...)
34     __attribute__((__format__(printf, 2, 3)));
35 int test_vasprintf(char **, const char *, va_list);
36 #endif
37
38
39 int
40 asprintf(char **strp, const char *fmt, ...)
41 {
42     va_list args;
43     int status;
44
45     va_start(args, fmt);
46     status = vasprintf(strp, fmt, args);
47     va_end(args);
48     return status;
49 }
50
51
52 int
53 vasprintf(char **strp, const char *fmt, va_list args)
54 {
55     va_list args_copy;
56     int status, needed, oerrno;
57
58     va_copy(args_copy, args);
59     needed = vsnprintf(NULL, 0, fmt, args_copy);
60     va_end(args_copy);
61     if (needed < 0) {
62         *strp = NULL;
63         return needed;
64     }
65     *strp = malloc(needed + 1);
66     if (*strp == NULL)
67         return -1;
68     status = vsnprintf(*strp, needed + 1, fmt, args);
69     if (status >= 0)
70         return status;
71     else {
72         oerrno = errno;
73         free(*strp);
74         *strp = NULL;
75         errno = oerrno;
76         return status;
77     }
78 }