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

Memory leak in face of exceptions #118

Closed
ColinH opened this issue Sep 8, 2015 · 2 comments
Closed

Memory leak in face of exceptions #118

ColinH opened this issue Sep 8, 2015 · 2 comments

Comments

@ColinH
Copy link
Contributor

ColinH commented Sep 8, 2015

The constructor often does a two-step initialisation, an allocate() followed by a construct(). If the construct() throws then the previously allocated memory will leak...

        AllocatorType<object_t> alloc;
        object = alloc.allocate(1);
        alloc.construct(object, value);
@gregmarr
Copy link
Contributor

gregmarr commented Sep 8, 2015

Probably the least intrusive way is to use a temporary unique_ptr with a custom deleter:

    AllocatorType<object_t> alloc;
    auto deleter = [&](object_t *object) { alloc.deallocate(object, 1); };
    std::unique_ptr<object_t, decltype(deleter)> local_object(alloc.allocate(1), deleter);
    alloc.construct(local_object, value);
    object = local_object.release();

Another way would be with try/catch:

    AllocatorType<object_t> alloc;
    object = alloc.allocate(1);
    try {
        alloc.construct(object, value);
    } catch(...) {
        alloc.deallocate(object, 1);
        throw;
    }

Beyond that, it would probably require wrapping the m_value and m_type in a struct, and moving the basic_json destructor to the new struct.

@ColinH
Copy link
Contributor Author

ColinH commented Sep 8, 2015

Yes, either should work, not quite sure which style the author prefers.

nlohmann added a commit that referenced this issue Oct 3, 2015
exception-safe object creation, fixes #118
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants