json icon indicating copy to clipboard operation
json copied to clipboard

Fix json::update() with merge_objects==true error

Open DanielHwangbo opened this issue 1 month ago • 5 comments

Description

This PR fixes a crash when using update() on an ordered_json object when JSON_DIAGNOSTICS is enabled.

The Issue

When update() inserts new elements into an ordered_json object, the underlying std::vector may reallocate. This invalidates the m_parent pointers of existing children, causing assert_invariant to fail immediately because the children point to the old memory address.

The Fix

I have updated the update() function to call set_parents() after insertion operations when diagnostics are enabled. This ensures that if the container moves in memory, all children are correctly updated to point to the new parent address.

Reproduction Code

#define JSON_DIAGNOSTICS 1
#include "nlohmann/json.hpp"
#include <iostream>

int main() {
    using json = nlohmann::ordered_json;
    json j1 = { {"numbers", {{"one", 1}}} };
    json j2 = { {"numbers", {{"two", 2}}}, {"string", "t"} };

    // This triggers reallocation and assertion failure without the fix
    j1.update(j2, true); 
    std::cout << j1.dump() << std::endl;
}

DanielHwangbo avatar Nov 30 '25 03:11 DanielHwangbo

Coverage Status

coverage: 99.176% (-0.02%) from 99.191% when pulling f7e256e0a95c45a38231fbf60ef713eaad386e2e on DanielHwangbo:issue4813 into a0e9fb1e638cfbb5b8b556b7c51eaa81977bad48 on nlohmann:develop.

coveralls avatar Nov 30 '25 09:11 coveralls

🔴 Amalgamation check failed! 🔴

The source code has not been amalgamated. @DanielHwangbo Please read and follow the Contribution Guidelines.

github-actions[bot] avatar Nov 30 '25 10:11 github-actions[bot]

Maybe related: #4813

nlohmann avatar Nov 30 '25 11:11 nlohmann

Hi nlohmann,

I have fixed the Amalgamation error and would like to request a code review again!

DanielHwangbo avatar Dec 08 '25 01:12 DanielHwangbo

🔴 Amalgamation check failed! 🔴

The source code has not been amalgamated. @DanielHwangbo Please read and follow the Contribution Guidelines.

github-actions[bot] avatar Dec 08 '25 05:12 github-actions[bot]