0

In the JSONCPP library's documentation ( here ), it says that the function Json::parseFromStream() accepts a Json::Value * as one of its arguments. However it results in a segmentation fault as in the following snippet :

   void Coco::read_gt(const std::string filename){
        if (!file_exists(&filename)){
            throw std::invalid_argument("The file " + filename + " ws not found." );
        }
        Json::CharReaderBuilder builder{};
        builder["collectComments"] = false;
        Json::Value *  value = nullptr;
        std::string errs{};
        std::ifstream fid(filename);
        LOG(INFO) << "HERE";
        bool ok = Json::parseFromStream(builder, fid, value, &errs);
        std::cout << ok << std::endl;
        value->removeMember("licenses");
        gt = value;
        return;
    }

Interestingly when I use a reference as against the documentation, I do not get a segmentation fault as in the following snippet

void Coco::read_gt(const std::string filename){
    if (!file_exists(&filename)){
        throw std::invalid_argument("The file " + filename + " ws not found." );
    }
    Json::CharReaderBuilder builder{};
    builder["collectComments"] = false;
    Json::Value  value;
    std::string errs{};
    std::ifstream fid(filename);
    LOG(INFO) << "HERE";
    bool ok = Json::parseFromStream(builder, fid, &value, &errs);
    std::cout << ok << std::endl;
    value->removeMember("licenses");
    gt = value;
    return;
}

What is the possible reason for this behavior ?

  • 1
    `nullptr` is not a right place to put values. – MikeCAT Jul 15 '21 at 11:46
  • "_Interestingly when I use a reference as against the documentation, I do not get a segmentation fault as in the following snippet_" Where do you use a reference, in that snippet, where you didn't use in the previous example? `&` in `&value` doesn't denote a reference. In that context, it's address-of operator. – Algirdas Preidžius Jul 15 '21 at 11:46
  • Hello, Even without using a `nullptr` , I get a segmentation fault. For the second point, I concur. It is the address indeed. But why does the fault persist when I do not use a `nullptr` ? – ujjwal.researcher Jul 15 '21 at 11:49
  • If you don't assign `nullptr` - the pointer has indeterminate value - which is, still, not a valid memory to write to. Technically, even reading such variable invokes undefined behavior. In the 2nd example, you provide a pointer to a valid `Json::Value` object. – Algirdas Preidžius Jul 15 '21 at 13:20

0 Answers0