Posted on September 15th, 2008 at 0:48 by fr3@K
In a blog post Danny Kalev published earlier this year on InformIT, an example was presented demonstrating how one could write valid but insecure code involving vector and auto_ptr which compiles without any warning, despite other warnings Micorsoft’s recent compilers would’ve issued against standard compliant code. Along with other points he made in the post, Danny suggests Micorsoft doesn’t really care about your code safety. I couldn’t have agreed with him more, and would like to contribute my own analysis (aka. my two cents) in support of Danny’s finding.
Most of us are very well aware of the often-exploited security vulnerability in
strcpy, and Microsoft’s answer to it is strcpy_s, which is said to be a more secure alternative that takes an additional parameter, numberOfElements as they called it:
char *strcpy( char *strDestination, const char *strSource ); errno_t strcpy_s( char *strDestination, size_t numberOfElements, const char *strSource );
But wait, doesn’t strcpy_s look awfully similar to another standard function?
char *strncpy( char *strDest, const char *strSource, size_t count );
Put aside the subtle differences in types of return value and parameter naming/ordering, and the insignificant behavioral difference (in regard to buffer overruns, which only applies when things start to screw up) when numberOfElements/count is too small. They are effectively the same.
Yes, I get the semantical differentiation Micorsoft has been trying to sell us programmers. But I failed to understand how is strcpy_s more secure than strncpy syntactically.
Wouldn’t it make more sense if compiler vendors would educate programmers (a.k.a. their customers) the habit of using strncpy instead of strcpy, and use count as the size of the memory buffer strDest points to, for security reasons. But, no, Microsoft had to tell programmers to embrace their proprietary Security Enhanced CRT functions and hints, in a security note, that we can’t use strncpy safely:
strncpy does not check for sufficient space in strDest; it is therefore a potential cause of buffer overruns. Keep in mind that count limits the number of characters copied; it is not a limit on the size of strDest.
If the parameter count couldn’t buy strncpy security, I just don’t see how strcpy_s could have made the cut with numberOfElements.
![]() |
|
| Previous Post « How to Do It Right? Wide and Multi-Byte String Conversion « |
Next Post » Microsoft Search SPAM is back » |








除了使用 strcpy() 的習慣早就應該改為 strncpy() 以外,
就連 fopen()、sprintf()、fscanf() 等等也會跳出討厭的 warnings。
使用這些 _s 版本的函式真的會比較安全嗎?
Comment by 半路 — September 25, 2008 @ 13:41