Skip to content

~basic_json can terminate program #4653

@Ignition

Description

@Ignition

Description

During ~basic_json, it is possible to get an exception from the allocation subsystem (quota/policy violation etc). This should be expected and accounted for.

Either:

  • ~basic_json should not be using any allocation, OR
  • upon exception a non allocating alternative to destroy should be used.

Reproduction steps

Throw any exception when allocation request is made during ~basic_json

Expected vs. actual results

Expected: ~basic_json should not terminate a program.
Actual: it terminates the program

Minimal code example

#include <nlohmann/json.hpp>
using json = nlohmann::json;

thread_local bool should_throw = false;

struct QuotaReached : std::exception {};

void* operator new(std::size_t size) {
    if (should_throw){
        throw QuotaReached{};
    }
    void* ptr = std::malloc(size);
    if (!ptr) {
        throw std::bad_alloc();
    }
    return ptr;
}

int main()
{
    {
        auto j = json{1,2,3,4};
        should_throw = true;
        // `j` is destroyed, ~basic_json is noexcept
        // allocation attempted, exception thrown
        // terminate is called
    }
}

https://godbolt.org/z/zh41cxW8j

Error messages

terminate called after throwing an instance of 'QuotaReached'
  what():  std::exception
Program terminated with signal: SIGSEGV

Compiler and operating system

gcc 14.2 Linux

Library version

3.11.1

Validation

Metadata

Metadata

Assignees

No one assigned

    Labels

    kind: bugstate: stalethe issue has not been updated in a while and will be closed automatically soon unless it is updated

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions