-
Notifications
You must be signed in to change notification settings - Fork 0
/
safe_string.template.cpp
99 lines (73 loc) · 1.61 KB
/
safe_string.template.cpp
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <windows.h>
#include <wchar.h>
#include <stdarg.h>
// C++ only
template <size_t size>
int _cdecl safe_sprintf(char (&buffer)[size],
const char *format, ...)
{
memset(buffer, 0, size * sizeof(char));
if (NULL == format)
return -1;
va_list ap;
va_start(ap, format);
int res = -1;
res = _vsnprintf_s(buffer, size, _TRUNCATE,
format, ap);
va_end(ap);
return res;
}
// C++ only
template <size_t size>
int _cdecl safe_sprintf(wchar_t (&buffer)[size],
const wchar_t *format, ...)
{
memset(buffer, 0, size * sizeof(wchar_t));
if (NULL == format)
return -1;
va_list ap;
va_start(ap, format);
int res = -1;
res = _vsnwprintf_s(buffer, size, _TRUNCATE,
format, ap);
va_end(ap);
return res;
}
// C++ only
template <size_t size>
int _cdecl safe_overwrite(char (&buffer)[size],
const char *format, ...)
{
if (NULL == format)
return -1;
char *interim = (char*) calloc(size, sizeof(char));
va_list ap;
va_start(ap, format);
int res = -1;
res = _vsnprintf_s(interim, size, _TRUNCATE,
format, ap);
va_end(ap);
memset(buffer, 0, size * sizeof(char));
memcpy(buffer, interim, size);
free(interim), interim = NULL;
return res;
}
// C++ only
template <size_t size>
int _cdecl safe_overwrite(wchar_t (&buffer)[size],
const wchar_t *format, ...)
{
if (NULL == format)
return -1;
wchar_t *interim = (wchar_t*) calloc(size, sizeof(wchar_t));
va_list ap;
va_start(ap, format);
int res = -1;
res = _vsnwprintf_s(interim, size, _TRUNCATE,
format, ap);
va_end(ap);
wmemset(buffer, 0, size);
wmemcpy(buffer, interim, size);
free(interim), interim = NULL;
return res;
}