Skip to content
This repository was archived by the owner on Dec 20, 2023. It is now read-only.

Commit cbc27c4

Browse files
committed
Do not try to allocate memory on de-serialization when there is no need
to do so(empty strings). Also, do not attempt to free a string if empty.
1 parent 9708816 commit cbc27c4

File tree

1 file changed

+21
-11
lines changed

1 file changed

+21
-11
lines changed

src/lib/support/SerializationUtils.cpp

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -877,31 +877,41 @@ WEAVE_ERROR ReadDataForType(TLVReader &aReader, void *aStructureData, const Fiel
877877

878878
case SerializedFieldTypeUTF8String:
879879
{
880-
char *dst = NULL;
881880
// TLV Strings are not null terminated
882881
uint32_t length = aReader.GetLength() + 1;
883882

884-
dst = (char *)memMgmt->mem_alloc(length);
885-
VerifyOrExit(dst != NULL, err = WEAVE_ERROR_NO_MEMORY);
883+
if (length > 1)
884+
{
885+
char *dst = NULL;
886886

887-
err = aReader.GetString(dst, length);
888-
SuccessOrExit(err);
887+
dst = (char *)memMgmt->mem_alloc(length);
888+
VerifyOrExit(dst != NULL, err = WEAVE_ERROR_NO_MEMORY);
889+
890+
err = aReader.GetString(dst, length);
891+
SuccessOrExit(err);
892+
893+
LogReadWrite("%s utf8string '%s' allocating %d bytes at %p", "R", dst, length, dst);
889894

890-
LogReadWrite("%s utf8string '%s' allocating %d bytes at %p", "R", dst, length, dst);
891-
*static_cast<char**>(aStructureData) = dst;
895+
*static_cast<char**>(aStructureData) = dst;
896+
}
892897
break;
893898
}
894899

895900
case SerializedFieldTypeByteString:
896901
{
897902
SerializedByteString byteString;
898903
byteString.mLen = aReader.GetLength();
904+
byteString.mBuf = NULL;
905+
906+
if (byteString.mLen > 0)
907+
{
908+
byteString.mBuf = static_cast<uint8_t *>(memMgmt->mem_alloc(byteString.mLen));
909+
VerifyOrExit(byteString.mBuf != NULL, err = WEAVE_ERROR_NO_MEMORY);
910+
aReader.GetBytes(byteString.mBuf, byteString.mLen);
899911

900-
byteString.mBuf = static_cast<uint8_t *>(memMgmt->mem_alloc(byteString.mLen));
901-
VerifyOrExit(byteString.mBuf != NULL, err = WEAVE_ERROR_NO_MEMORY);
902-
aReader.GetBytes(byteString.mBuf, byteString.mLen);
912+
LogReadWrite("%s bytestring allocated %d bytes at %p", "R", byteString.mLen, byteString.mBuf);
913+
}
903914

904-
LogReadWrite("%s bytestring allocated %d bytes at %p", "R", byteString.mLen, byteString.mBuf);
905915
*static_cast<SerializedByteString *>(aStructureData) = byteString;
906916
break;
907917
}

0 commit comments

Comments
 (0)