Skip to content

Commit

Permalink
Fix memory leak on assignment and move operators
Browse files Browse the repository at this point in the history
  • Loading branch information
st235 committed Jul 26, 2024
1 parent d1d850b commit 617e971
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 16 deletions.
3 changes: 2 additions & 1 deletion CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
40 changes: 25 additions & 15 deletions include/json.h
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,9 @@ class Json {

ValueContainer& operator=(const ValueContainer& that) noexcept {
if (this != &that) {
// Delete old value.
deleteContainerValue();

type = that.type;
copyContainerValue(that);
}
Expand All @@ -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));
}
Expand All @@ -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:
Expand Down Expand Up @@ -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;
Expand Down

0 comments on commit 617e971

Please sign in to comment.