I'm sure there are a lot of buffer overflow risks in coding, many of which are addressed by standard library's "_s" safe functions. Nonetheless, I find myself confused, from time to time, on some of them.
Let's say I have some fragment like this
uint8_t a[5];
...
size_t z = 6;
...
memset(a, 0, z); // Overflow!
Some compilers (C11) may advise better use of memset_s
; as I'm a lousy programmer I just updated my code to this brand new thing, my way:
uint8_t a[5];
...
rsize_t max_array = 56; // Slipped finger, head in the clouds, etc.
rsize_t z = 6;
...
memset_s(a, max_array, 0, z); // So what?
How would memset_s
be any better than memset
if I'm just adding the error to another parameter?
Where is the added safety, if adding a new parameter simply adds a new parameter that can be wrong. I could have corrected my code in the first revision, and still have a legal call to a well-defined operation on a buffer.
Left apart the case with an unchecked zero pointer, how could memset
be that much worse than memset_s
?
[EDIT]
With a little effort, I also found what setting was causing the warning in my setup. This may be of help for someone.
The warning comes from Clang-tidy, invoked in the Visual Studio extension "Clang power tools".
In its default setup, it enables for Clang-tidy the checker "security.insecureAPI.DeprecatedOrUnsafeBufferHandling" which mimics the default MSVC warnings. Note that this isn't available from command line options (or at least is not listed among them), but read from a .clang-tidy file.
In the first runs, I didn't even have a .clang-tidy file, although that was enforced by default.
In my case, the reason for the message appearing in Clang-tidy and not with MSVC is straightforward.
I defined in my code
#define _CRT_SECURE_NO_WARNINGS
to not be infested by MSVC warnings, but this method is ineffective with Clang-tidy, which kept nagging me (due to Clang power tools defaults)
memset_s(a, sizeof a, 0, z);
but I agree that it doesn't add much safety.