What are some alternatives to the Microsoft security enhanced functions such as strncpy_s
or _itoa_s
? Although developing in MS environment the goa
Just use strncpy and disable the warning in VC++.
std::string s(Cstring, n);
You could either provide an own implementation for platforms that don't have this function. Or use a macro to reduce the arguments by one and map to the standard string function.
You may be interested in the Apache Portable Runtime project:
The mission of the Apache Portable Runtime (APR) project is to create and maintain software libraries that provide a predictable and consistent interface to underlying platform-specific implementations.
autoconf can also take care of some of these platform-specific differences (by setting #defines, etc), although my experience with it under Windows leaves something to be desired.
If you really want to program in C:
Use the plain old standard strncpy
.
If you're programming in C++:
Use the plain old standard string class std::string
.
(hint: You probably want the latter. C strings are just bugs waiting to happen, even if you use the "secure" *_s
functions. C++ added a string class for a reason)
Yes, try the https://rurban.github.io/safeclib/.
This is the platform independent implementation of the C11 Annex K on top of all libc's. It is mostly compatible to the Windows sec_api. Windows deviates a bit from the spec with some functions.
strncpy_s
is one of the most tricky APIs in the sec_api. Windows does not detect overflow of the two lengths, not an overlap of the two strings.
And what to do when the 4th argument count = 0 is also questionable. The spec http://en.cppreference.com/w/c/string/byte/strncpy says A zero return value implies ... that the result in s1 is null terminated, but on windows this is wrong. It just aborts too early.
See e.g. the wine implementation: https://github.com/mirror/reactos/blob/master/reactos/lib/sdk/crt/wine/heap.c#L577
And for the _s
secure suffix one should assume that wrongly copied bytes into the destination buffer are cleared from prying eyes when an run-time error occured. Not so on Windows with their sec_api. They just set the very first byte to 0.
https://github.com/rurban/safeclib/releases