diff --git a/src/lib/support/CHIPMemString.h b/src/lib/support/CHIPMemString.h index 51341192a76250..3b74acdbcaf195 100644 --- a/src/lib/support/CHIPMemString.h +++ b/src/lib/support/CHIPMemString.h @@ -82,12 +82,20 @@ inline void CopyString(char (&dest)[N], const char * source) */ inline void CopyString(char * dest, size_t destLength, ByteSpan source) { - if (dest && destLength) + if ((dest == nullptr) || (destLength == 0)) { - size_t maxChars = std::min(destLength - 1, source.size()); - memcpy(dest, source.data(), maxChars); - dest[maxChars] = '\0'; + return; // no space to copy anything, not even a null terminator } + + if (source.empty()) + { + *dest = '\0'; // just a null terminator, we are copying empty data + return; + } + + size_t maxChars = std::min(destLength - 1, source.size()); + memcpy(dest, source.data(), maxChars); + dest[maxChars] = '\0'; } /**