From af9914437609bb1eaee4c65a76aae1a7fdd90a90 Mon Sep 17 00:00:00 2001 From: Ronan Abhamon Date: Fri, 15 Dec 2017 11:36:19 +0100 Subject: [PATCH] fix(utils): avoid memory leak in utf8 conversions --- include/linphone/utils/utils.h | 4 ++++ src/utils/utils.cpp | 19 +++++++++++++------ 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/include/linphone/utils/utils.h b/include/linphone/utils/utils.h index fa0a55db8..6bca0933b 100644 --- a/include/linphone/utils/utils.h +++ b/include/linphone/utils/utils.h @@ -99,6 +99,10 @@ namespace Utils { // Return a buffer allocated with new. LINPHONE_PUBLIC char *utf8ToChar (uint32_t ic); + LINPHONE_PUBLIC inline std::string cStringToCppString (const char *str) { + return str ? str : ""; + } + template LINPHONE_PUBLIC const T &getEmptyConstRefObject () { static const T object; diff --git a/src/utils/utils.cpp b/src/utils/utils.cpp index c60a8141c..2c2216ef3 100644 --- a/src/utils/utils.cpp +++ b/src/utils/utils.cpp @@ -187,19 +187,26 @@ long Utils::getTmAsTimeT (const tm &time) { // ----------------------------------------------------------------------------- +// TODO: Improve perf!!! Avoid c <--> cpp string conversions. string Utils::localeToUtf8 (const string &str) { - char *ret = bctbx_locale_to_utf8(str.c_str()); - return string(ret != NULL ? ret : ""); + char *cStr = bctbx_locale_to_utf8(str.c_str()); + string utf8Str = cStringToCppString(cStr); + bctbx_free(cStr); + return utf8Str; } string Utils::utf8ToLocale (const string &str) { - char *ret = bctbx_utf8_to_locale(str.c_str()); - return string(ret != NULL ? ret : ""); + char *cStr = bctbx_utf8_to_locale(str.c_str()); + string localeStr = cStringToCppString(cStr); + bctbx_free(cStr); + return localeStr; } string Utils::convertString (const string &str, const string &from, const string &to) { - char *ret = bctbx_convert_from_to(str.c_str(), from.c_str(), to.c_str()); - return string(ret != NULL ? ret : ""); + char *cStr = bctbx_convert_from_to(str.c_str(), from.c_str(), to.c_str()); + string convertedStr = cStringToCppString(cStr); + bctbx_free(cStr); + return convertedStr; } LINPHONE_END_NAMESPACE