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

segmentation fault when iterating over empty arrays/objects #28

Closed
nlohmann opened this issue Jan 13, 2015 · 1 comment
Closed

segmentation fault when iterating over empty arrays/objects #28

nlohmann opened this issue Jan 13, 2015 · 1 comment
Assignees

Comments

@nlohmann
Copy link
Owner

From an email:

Anyway, a quite serious bug is when one tries to iterate over a empty container (array or object), which results in a segmentation fault due to a 0x0 this pointer. I fixed this by changing the iterator constructors to check if the container is empty, and in that case set the “object_” pointer to a nullptr.

The proposed code fix:

json::const_iterator::const_iterator(const json* j) : object_(j)
{
    if (object_ != nullptr)
    {
        if (object_->type_ == value_type::array)
        {
            if (object_->empty())
// Explicit empty check added
            {
                object_ = nullptr;
            }
            else
            {
                vi_ = new array_t::const_iterator(object_->value_.array->begin());
            }
        }
        else if (object_->type_ == value_type::object)
// *else if* is mandatory since the previous
        {
// block can set pointer to nullptr!
            if (object_->empty())
// Explicit empty check added
            {
                object_ = nullptr;
            }
            else
            {
                oi_ = new object_t::const_iterator(object_->value_.object->begin());
            }
        }
    }
}
@nlohmann
Copy link
Owner Author

The bug can be reproduced with the following code:

json j(json::value_type::array);
for (json::iterator it = j.begin(); it != j.end(); ++it) {}

@nlohmann nlohmann self-assigned this Jan 13, 2015
GerHobbelt pushed a commit to GerHobbelt/nlohmann-json that referenced this issue May 7, 2021
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

1 participant