by rurban · 7y ago · 0 comments
This worse than the wchar_t iswalpha trouble with older UCS-2 implementations (Windows, AIX).
Or the implementation trouble with memset, which either can be optimized away without a compiler barrier, or on modern hyperthreaded microarchitectures which violate load-store ordering and thus need a full memory barrier (mfence). no single libc does it properly, not even crypto libs, such as libsodium.
strncpy is commonly misused as a strlcpy, though, in part because glibc continues to refuse to add strlcpy. strlcpy provides the functionality most people want from strncpy but do not get.
Can you give an example of the strncpy problem?
Also is there a precaution programs can take to use memset more safely?
And yes, maybe it'll impact performance. Worry about that _after_ you profile your code and have the numbers to show it -- I'd bet good money that 95% of developers will never need to worry about it.
So to be on the safe side you need to wrap strncpy calls into a function that always puts a '\0' on the very last index of the destination string buffer.
As for memset, the best workaround is to use OS specific variants that aren't subject to such issues, for example SecureZeroMemory() on Windows.
In reality the compiler should know about the libc memset and memzero and refuse to optimize it away, and memset_s/SecureZeroMemory needs a memory barrier.
The strncpy truncating problem is widely known: https://www.google.com/search?q=strncpy+truncating+problem
But conceptually the biggest problem is the inability to deal with strings properly at all. You mentioned the iswalpha problem and the need for external libs, but the standard cannot even search for unicode strings properly (no normalization wcsnorm, no wcsfc, no UTF-8 u8 API), ditto sorting needs an API for the unicode version being used. It's relative and changes every year. And every libc is hopelessly behind. The most basic coreutils still cannot search for foreign strings (grep, sort, wc, cut, expand, ...): http://perl11.org/blog/foldcase.html https://crashcourse.housegordon.org/coreutils-multibyte-supp...
http://the-flat-trantor-society.blogspot.com/2012/03/no-strn...