Skip to content

Instantly share code, notes, and snippets.

@hkuno9000
Last active December 18, 2021 17:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hkuno9000/64632116057bc985220125a99e051b46 to your computer and use it in GitHub Desktop.
Save hkuno9000/64632116057bc985220125a99e051b46 to your computer and use it in GitHub Desktop.
// wrapper functions to fix C4996 on VS2019
//#include <string.h>
//#include <stdlib.h>
//#include <stdio.h>
//#include <wchar.h>
//#include <tchar.h>
template <typename T> T* malloc_array(rsize_t size) {
return static_cast<T*>(malloc(sizeof(T) * size));
}
inline char* new_and_strcpy_s(const char* src, rsize_t size) {
auto dest = new char[size];
strcpy_s(dest, size, src); // if dest is nullptr, strcpy_s returns EINVAL and dose not touch dest.
return dest;
}
inline wchar_t* new_and_wcscpy_s(const wchar_t* src, rsize_t size) {
auto dest = new wchar_t[size];
wcscpy_s(dest, size, src); // if dest is nullptr, strcpy_s returns EINVAL and dose not touch dest.
return dest;
}
inline TCHAR* new_and_tcscpy_s(const TCHAR* src, rsize_t size) {
auto dest = new TCHAR[size];
_tcscpy_s(dest, size, src); // if dest is nullptr, strcpy_s returns EINVAL and dose not touch dest.
return dest;
}
inline char* malloc_and_strcpy_s(const char* src, rsize_t size) { // like as _strdup(src)
auto dest = malloc_array<char>(size);
strcpy_s(dest, size, src); // if dest is nullptr, strcpy_s returns EINVAL and dose not touch dest.
return dest;
}
inline wchar_t* malloc_and_wcscpy_s(const wchar_t* src, rsize_t size) { // like as _wcsdup(src)
auto dest = malloc_array<wchar_t>(size);
wcscpy_s(dest, size, src); // if dest is nullptr, strcpy_s returns EINVAL and dose not touch dest.
return dest;
}
inline TCHAR* malloc_and_tcscpy_s(const TCHAR* src, rsize_t size) { // like as _tcsdup(src)
auto dest = malloc_array<TCHAR>(size);
_tcscpy_s(dest, size, src); // if dest is nullptr, strcpy_s returns EINVAL and dose not touch dest.
return dest;
}
#ifdef _AFX
inline TCHAR* new_and_tcscpy_s(const CString& cstr) {
return new_and_tcscpy_s(cstr, cstr.GetLength()+1);
}
inline TCHAR* malloc_and_tcscpy_s(const CString& cstr) { // same as _tcsdup(cstr)
return malloc_and_tcscpy_s(cstr, cstr.GetLength()+1);
}
#endif
inline FILE* fopen_s_wrapper(const char* fname, const char* mode) {
FILE* fp = nullptr;
auto error = fopen_s(&fp, fname, mode);
return (error == 0) ? fp : nullptr;
}
inline FILE* wfopen_s_wrapper(const wchar_t* fname, const wchar_t* mode) {
FILE* fp = nullptr;
auto error = _wfopen_s(&fp, fname, mode);
return (error == 0) ? fp : nullptr;
}
inline FILE* tfopen_s_wrapper(const TCHAR* fname, const TCHAR* mode) {
FILE* fp = nullptr;
auto error = _tfopen_s(&fp, fname, mode);
return (error == 0) ? fp : nullptr;
}
// end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment