-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathasprintf.c
77 lines (63 loc) · 1.63 KB
/
asprintf.c
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include "asprintf.h"
#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64)
#if _MSC_VER < 1800
#undef va_copy
#define va_copy(dst, src) (dst = src)
#endif
#ifdef __cplusplus
extern "C"
#endif
int vasprintf(char** strp, const char* fmt, va_list ap)
{
va_list ap_copy;
int formattedLength, actualLength;
size_t requiredSize;
// be paranoid
*strp = NULL;
// copy va_list, as it is used twice
va_copy(ap_copy, ap);
// compute length of formatted string, without NULL terminator
formattedLength = _vscprintf(fmt, ap_copy);
va_end(ap_copy);
// bail out on error
if (formattedLength < 0)
{
return -1;
}
// allocate buffer, with NULL terminator
requiredSize = ((size_t)formattedLength) + 1;
*strp = (char*)malloc(requiredSize);
// bail out on failed memory allocation
if (*strp == NULL)
{
errno = ENOMEM;
return -1;
}
// write formatted string to buffer, use security hardened _s function
actualLength = vsnprintf_s(*strp, requiredSize, requiredSize - 1, fmt, ap);
// again, be paranoid
if (actualLength != formattedLength)
{
free(*strp);
*strp = NULL;
errno = EOTHER;
return -1;
}
return formattedLength;
}
#ifdef __cplusplus
extern "C"
#endif
int asprintf(char** strp, const char* fmt, ...)
{
int result;
va_list ap;
va_start(ap, fmt);
result = vasprintf(strp, fmt, ap);
va_end(ap);
return result;
}
#endif