Making secure programming hard through bad documentation.
I ran into a little confusion when tracking down a bug in one of my programs today.
Direct quote from the sscanf_s formatting fields documentation (as of the time of posting, maybe it'll be corrected soon):
"The secure versions (those with the _s suffix) of the scanf family of functions require that a buffer size parameter be passed preceding each parameter of type c, C, s, S or [."
Uh... that should be "following"(or even "after", because people understand short words better), not "preceding", and an example would be good to make this distinction clear:
// Read a maximum of 19 characters and a null from input_string.
errval = sscanf_s( input_string,
This reminds me - I take a lot of time impressing on developers the difference between _countof and sizeof.
The sizeof operator (it's not a function - don't get confused by "sizeof x", and expect "sizeof(x)") has the advantage of being straight C, but it has the disadvantage of frequently returning 4 (the usual size of a pointer), or in Unicode programming, twice the amount you're looking for.
_countof() is a compile-time evaluation through smart use of C++ templates - when you accidentally pass it a pointer instead of an array, you get a compile error (a good thing!), and it always returns the value you're looking for in order to use the secure _s functions.
The documentation for those secure "_s" string functions could be far clearer on this point, too - so much of the documentation refer to phrases like "the count parameter is a count of bytes for char, and a count of characters for wchar", or "Parameters: sizeInBytes, sizeInWords" - no, it's always a count of characters, and if you think of it in such an unambiguous way as "count of characters", you will be less confused.
IMHO, sizeof should be reserved for the strict exact case of requiring to know how many bytes in memory an object will occupy - for when you're treating the destination as a pointer to memory, not characters of any sort (not even one-byte characters). _countof, where available, should be used in preference, to get the number of elements.
This ties into my earlier topic on SAL - _ecount should be used in preference to _bcount in SAL annotations, because you are dealing with the elements of an array, not the bytes at a memory address.
I know C++ allows you to think and code in the lowest levels, but that is not an invitation to always do so - take advantage of high-level constructs when dealing with high-level concepts ("string" is a significantly higher concept that "pointer to byte sequence").