Skip to content

Inja invalid memory access in loops due to missing pointer stability when using INJA_DATA_TYPE=nlohmann::ordered_json #289

Open
@Naios

Description

0066e60

Thank you for your awesome library, it works very well.

I have been trying to process an ordered json that I have generated with nlohmann::ordered_json.
Therefore, I have defined INJA_DATA_TYPE as nlohmann::ordered_json.

It seems that the code that processes the loop object iteration has issues with missing pointer stability in this case:

    if (!current_loop_data->empty()) {
      (*current_loop_data)["parent"] = std::move(*current_loop_data);
    }

    size_t index = 0;
    (*current_loop_data)["is_first"] = true;
    (*current_loop_data)["is_last"] = (result->size() <= 1);
    for (auto it = result->begin(); it != result->end(); ++it) {
      additional_data[static_cast<std::string>(node.key)] = it.key();
      additional_data[static_cast<std::string>(node.value)] = it.value();

      (*current_loop_data)["index"] = index;
      // ^^^^ first invalid access here
      (*current_loop_data)["index1"] = index + 1;
      if (index == 1) {
        (*current_loop_data)["is_first"] = false;
      }
      if (index == result->size() - 1) {
        (*current_loop_data)["is_last"] = true;
      }

It seems current_loop_data points to an invalid memory location in this case if the elements in the ordered map gets shifted around or are reallocated.
While this seems to work with the unordered nlohmann::json, it breaks when using nlohmann::ordered_json.
Also it seems that nlohmann::json does not document to provide stable pointers either, so maybe your library currently relies on this behaviour, without nlohmann::json providing official support for it.


This can be reproduced with:

Define: INJA_DATA_TYPE=nlohmann::ordered_json

{
  "objects": {
    "a": { },
    "b": { }
  }
}
{% for object_name, object in objects %}
- {{object_name}}
{% endfor %}

Thank you in advance.

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions