From 3c97e6a7d95653d81a00cc1f2274270fc577ec0d Mon Sep 17 00:00:00 2001 From: George Burgess IV Date: Wed, 20 Jan 2021 17:24:45 -0800 Subject: androidfw: use a vector instead of manually managing memory The static analyzer caught a memory leak in this code: > frameworks/base/libs/androidfw/ResourceTypes.cpp:1042:45: warning: Potential leak of memory pointed to by 'convBuffer' [clang-analyzer-unix.Malloc] We can use a `std::vector` to hold our fixed-size, heap-allocated array. This will manage its own buffer for us. Bug: None Test: TreeHugger Change-Id: Ib83bdbc0bc60304747676e924f2ff549840aa861 --- libs/androidfw/ResourceTypes.cpp | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) (limited to 'libs') diff --git a/libs/androidfw/ResourceTypes.cpp b/libs/androidfw/ResourceTypes.cpp index bce70e2aae9e..223382731bc0 100644 --- a/libs/androidfw/ResourceTypes.cpp +++ b/libs/androidfw/ResourceTypes.cpp @@ -30,6 +30,7 @@ #include #include #include +#include #include #include @@ -1029,7 +1030,7 @@ base::expected ResStringPool::indexOfString(const char16_ // But we don't want to hit the cache, so instead we will have a // local temporary allocation for the conversions. size_t convBufferLen = strLen + 4; - char16_t* convBuffer = (char16_t*)calloc(convBufferLen, sizeof(char16_t)); + std::vector convBuffer(convBufferLen); ssize_t l = 0; ssize_t h = mHeader->stringCount-1; @@ -1043,8 +1044,8 @@ base::expected ResStringPool::indexOfString(const char16_ } if (s.has_value()) { char16_t* end = utf8_to_utf16(reinterpret_cast(s->data()), - s->size(), convBuffer, convBufferLen); - c = strzcmp16(convBuffer, end-convBuffer, str, strLen); + s->size(), convBuffer.data(), convBufferLen); + c = strzcmp16(convBuffer.data(), end-convBuffer.data(), str, strLen); } if (kDebugStringPoolNoisy) { ALOGI("Looking at %s, cmp=%d, l/mid/h=%d/%d/%d\n", @@ -1054,7 +1055,6 @@ base::expected ResStringPool::indexOfString(const char16_ if (kDebugStringPoolNoisy) { ALOGI("MATCH!"); } - free(convBuffer); return mid; } else if (c < 0) { l = mid + 1; @@ -1062,7 +1062,6 @@ base::expected ResStringPool::indexOfString(const char16_ h = mid - 1; } } - free(convBuffer); } else { // It is unusual to get the ID from an unsorted string block... // most often this happens because we want to get IDs for style -- cgit v1.2.3