From 617e9715a54344476a5c53a9ade5d02c5e555491 Mon Sep 17 00:00:00 2001 From: Alex Dadukin Date: Fri, 26 Jul 2024 23:00:51 +0100 Subject: [PATCH] Fix memory leak on assignment and move operators --- CMakeLists.txt | 3 ++- include/json.h | 40 +++++++++++++++++++++++++--------------- 2 files changed, 27 insertions(+), 16 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 674207b..5eeab4c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -71,9 +71,10 @@ if (COMPILE_TESTS) ) target_link_libraries(jsonc_tests PRIVATE jsonc) + target_include_directories(jsonc_tests PRIVATE ${CMAKE_CURRENT_LIST_DIR}/src) + # GMock is required to use EXPECT_THAT. target_link_libraries(jsonc_tests PRIVATE GTest::gtest_main GTest::gmock_main) - target_include_directories(jsonc_tests PRIVATE ${CMAKE_CURRENT_LIST_DIR}/src) # Enable all possible warnings and treat them as errors. # This check only affects tests builds, as if applied to diff --git a/include/json.h b/include/json.h index e4a9646..068b1e6 100644 --- a/include/json.h +++ b/include/json.h @@ -85,6 +85,9 @@ class Json { ValueContainer& operator=(const ValueContainer& that) noexcept { if (this != &that) { + // Delete old value. + deleteContainerValue(); + type = that.type; copyContainerValue(that); } @@ -99,6 +102,9 @@ class Json { ValueContainer& operator=(ValueContainer&& that) noexcept { if (this != &that) { + // Delete old value. + deleteContainerValue(); + type = that.type; swapContainerValue(std::move(that)); } @@ -107,21 +113,7 @@ class Json { } ~ValueContainer() { - switch (type) { - case kTypeNull: - case kTypeBool: - case kTypeNumber: - break; - case kTypeString: - delete value._string; - break; - case kTypeArray: - delete value._array; - break; - case kTypeObject: - delete value._object; - break; - } + deleteContainerValue(); } private: @@ -170,6 +162,24 @@ class Json { break; } } + + void deleteContainerValue() { + switch (type) { + case kTypeNull: + case kTypeBool: + case kTypeNumber: + break; + case kTypeString: + delete value._string; + break; + case kTypeArray: + delete value._array; + break; + case kTypeObject: + delete value._object; + break; + } + } }; static const Json VALUE_NULL;