nmsg  0.9.0
asprintf.c
1 /* imported from remctl-2.12 */
2 
3 /* Replacement for a missing asprintf and vasprintf.
4  *
5  * Provides the same functionality as the standard GNU library routines
6  * asprintf and vasprintf for those platforms that don't have them.
7  *
8  * Written by Russ Allbery <rra@stanford.edu>
9  * This work is hereby placed in the public domain by its author.
10  */
11 
12 #include <stdarg.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 
16 #include "asprintf.h"
17 
18 int
19 nmsg_asprintf(char **strp, const char *fmt, ...) {
20  va_list args;
21  int status;
22 
23  va_start(args, fmt);
24  status = nmsg_vasprintf(strp, fmt, args);
25  va_end(args);
26  return (status);
27 }
28 
29 int
30 nmsg_vasprintf(char **strp, const char *fmt, va_list args) {
31  va_list args_copy;
32  int status, needed;
33 
34  va_copy(args_copy, args);
35  needed = vsnprintf(NULL, 0, fmt, args_copy);
36  va_end(args_copy);
37  if (needed < 0) {
38  *strp = NULL;
39  return (needed);
40  }
41  *strp = malloc(needed + 1);
42  if (*strp == NULL)
43  return (-1);
44  status = vsnprintf(*strp, needed + 1, fmt, args);
45  if (status >= 0)
46  return (status);
47  else {
48  free(*strp);
49  *strp = NULL;
50  return (status);
51  }
52 }
Asprintf utility functions.