Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix memory leak on assignment and move operators #18

Merged
merged 1 commit into from
Jul 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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