summaryrefslogtreecommitdiff
path: root/src/libc/stdio/asprintf.c
blob: ee24e385cd01513d927d66f7ad203a13146a7d20 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <shared/mem.h>
#include <shared/printf.h>
#include <stdio.h>
#include <stdlib.h>

int asprintf(char **restrict sp, const char *restrict fmt, ...) {
	int ret;
	va_list argp;
	va_start(argp, fmt);
	ret = vasprintf(sp, fmt, argp);
	va_end(argp);
	return ret;
}
int vasprintf(char **restrict sp, const char *restrict fmt, va_list ap) {
	va_list ap2;
	va_copy(ap2, ap);
	int ret = vsnprintf(NULL, 0, fmt, ap2);
	va_end(ap2);

	if (ret < 0) return ret;
	*sp = malloc(ret+1);
	if (*sp == NULL) return -1;
	return vsnprintf(*sp, ret+1, fmt, ap);
}