diff --git a/src/lib/support/BufferWriter.cpp b/src/lib/support/BufferWriter.cpp index c606cba6e2b37d..2ba03e22d24e03 100644 --- a/src/lib/support/BufferWriter.cpp +++ b/src/lib/support/BufferWriter.cpp @@ -73,8 +73,9 @@ LittleEndian::BufferWriter & LittleEndian::BufferWriter::EndianPutSigned(int64_t BigEndian::BufferWriter & BigEndian::BufferWriter::EndianPut(uint64_t x, size_t size) { - while (size-- > 0) + while (size > 0) { + size--; Put(static_cast((x >> (size * 8)) & 0xff)); } return *this; @@ -82,8 +83,9 @@ BigEndian::BufferWriter & BigEndian::BufferWriter::EndianPut(uint64_t x, size_t BigEndian::BufferWriter & BigEndian::BufferWriter::EndianPutSigned(int64_t x, size_t size) { - while (size-- > 0) + while (size > 0) { + size--; Put(static_cast((x >> (size * 8)) & 0xff)); } return *this; 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'; } /**