Skip to content

Conversation

@DanielHwangbo
Copy link

@DanielHwangbo DanielHwangbo commented Nov 30, 2025

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;
}

@coveralls
Copy link

Coverage Status

coverage: 99.176% (-0.02%) from 99.191%
when pulling 0d1eb84 on DanielHwangbo:issue4813
into a0e9fb1 on nlohmann:develop.

@github-actions
Copy link

🔴 Amalgamation check failed! 🔴

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

@nlohmann
Copy link
Owner

Maybe related: #4813

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants