Do use strncpy in SafeStringCopy

I figured out how to mute the warnings.
This commit is contained in:
PJB3005
2026-03-27 17:16:41 +01:00
parent 96a61ed0b6
commit 0e1718e80d
+16 -14
View File
@@ -7,6 +7,17 @@
namespace dusk {
inline void strncpyProxy(char* dst, const char* src, size_t count) {
#if _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4996)
#endif
strncpy(dst, src, count);
#if _MSC_VER
#pragma warning(pop)
#endif
}
/**
* Copy a string to a fixed-size array.
* Truncates if the destination is not large enough, always inserts a null terminator (padding the remainder of the buffer with zeroes.)
@@ -15,13 +26,8 @@ template <size_t BufSize>
void SafeStringCopyTruncate(char (&buffer)[BufSize], const char* src) {
static_assert(BufSize > 0, "Target buffer cannot be size zero");
// Can't just use strncpy as I can't figure out how to selectively mute the warnings on MSVC.
// And can't use strncpy_s on MSVC as it doesn't fill the entire buffer.
constexpr size_t copyBufSize = BufSize - 1;
const auto srcLen = strlen(src);
const auto copyLen = srcLen > copyBufSize ? copyBufSize : srcLen;
memcpy(buffer, src, copyLen);
memset(buffer + copyLen, 0, BufSize - copyLen);
strncpyProxy(buffer, src, BufSize);
buffer[BufSize - 1] = 0;
}
/**
@@ -35,16 +41,12 @@ void SafeStringCopy(char (&buffer)[BufSize], const char* src) {
CRASH("Cannot copy string to same buffer");
}
// Can't just use strncpy as I can't figure out how to selectively mute the warnings on MSVC.
// And can't use strncpy_s on MSVC as it doesn't fill the entire buffer.
constexpr size_t copyBufSize = BufSize - 1;
const auto srcLen = strlen(src);
if (srcLen > copyBufSize) {
if (strlen(src) > BufSize - 1) {
CRASH("Destination buffer too small!");
}
memcpy(buffer, src, srcLen);
memset(buffer + srcLen, 0, BufSize - srcLen);
strncpyProxy(buffer, src, BufSize);
buffer[BufSize - 1] = 0;
}
}