Implement qstrncpy() in terms of std::strncat()

This has the advantage that we're only copying strlen(src) characters,
like in the strncpy_s() case, not fill all of [dst,len) with NULs,
like strncpy() is wont to do.

[ChangeLog][Important Behavior Changes][qstrncpy()] On non-Windows
platforms, no longer writes to all bytes of the target buffer, but
stops after the terminating NUL. This was already the behavior on
Windows.

Change-Id: Ic86206f418affae6d0d88dfe79537eeb833a7daa
Reviewed-by: Thiago Macieira <thiago.macieira@intel.com>
Reviewed-by: Mårten Nordheim <marten.nordheim@qt.io>
Reviewed-by: Edward Welbourne <edward.welbourne@qt.io>
bb10
Marc Mutz 2023-02-16 22:20:11 +01:00
parent c0a732f984
commit f030037d24
1 changed files with 3 additions and 10 deletions

View File

@ -133,16 +133,9 @@ char *qstrcpy(char *dst, const char *src)
char *qstrncpy(char *dst, const char *src, size_t len)
{
if (dst && len > 0) {
if (!src) {
*dst = '\0';
return nullptr;
}
#ifdef Q_CC_MSVC
strncpy_s(dst, len, src, len - 1);
#else
strncpy(dst, src, len);
#endif
dst[len-1] = '\0';
*dst = '\0';
if (src)
std::strncat(dst, src, len - 1);
}
return src ? dst : nullptr;
}