File: asprintf.c

package info (click to toggle)
ncap 1.9.2-8
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,704 kB
  • sloc: sh: 10,135; ansic: 5,829; perl: 68; makefile: 42; python: 33
file content (52 lines) | stat: -rw-r--r-- 1,089 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/* imported from remctl-2.12 */

/* Replacement for a missing asprintf and vasprintf.
 *
 * Provides the same functionality as the standard GNU library routines
 * asprintf and vasprintf for those platforms that don't have them.
 *
 * Written by Russ Allbery <rra@stanford.edu>
 * This work is hereby placed in the public domain by its author.
 */

#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>

#include "asprintf.h"

int
ncap_asprintf(char **strp, const char *fmt, ...) {
	va_list args;
	int status;

	va_start(args, fmt);
	status = ncap_vasprintf(strp, fmt, args);
	va_end(args);
	return (status);
}

int
ncap_vasprintf(char **strp, const char *fmt, va_list args) {
	va_list args_copy;
	int status, needed;

	va_copy(args_copy, args);
	needed = vsnprintf(NULL, 0, fmt, args_copy);
	va_end(args_copy);
	if (needed < 0) {
		*strp = NULL;
		return (needed);
	}
	*strp = malloc(needed + 1);
	if (*strp == NULL)
		return (-1);
	status = vsnprintf(*strp, needed + 1, fmt, args);
	if (status >= 0)
		return (status);
	else {
		free(*strp);
		*strp = NULL;
		return (status);
	}
}