在共享指针上看到意外数据

Tyl*_*iss 1 c++ shared-ptr

我正在尝试将nlohmann::json对象转换为std::shared_ptr<char[]>. 我遇到了一个问题,共享指针中的数据似乎附加了我原始对象中没有的额外垃圾。

下面的函数并不像它可能的那样简洁,因为我想展示我在调试器中看到的内容。您看到的注释是该行变量的值。我不明白这ÍýýýýÝÝÝÝÝ¡\x4\x1d'ýI是从哪里来的。我在这里做错了什么?

// Incoming json: {"data":[100]}
std::shared_ptr<char[]> serializeJson(nlohmann::json& d) {
    std::string ds = d.dump();                                // '{"data":[100]}'

    std::shared_ptr<char[]> rd(new char[ds.size() + 1]);     // 'ÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍýýýýÝÝÝÝÝ¡\x4\x1d'ýI'
    ds.copy(rd.get(), ds.size() + 1);                        // '{"data":[100]}ÍýýýýÝÝÝÝÝ¡\x4\x1d'ýI'

    return rd;
}
Run Code Online (Sandbox Code Playgroud)

我相信指针内的数据已被修改,因为当我尝试使用下面的函数对字符串进行反序列化时,出现异常。我也将值附加到此代码段中...

nlohmann::json deserializeJson(const std::shared_ptr<char[]>& d) {
    std::string p = d.get();                            // '{"data":[100]}ÍýýýýÝÝÝÝÝû¤¶¯´2'
    std::string e = p.substr(p.size()-10);              // 'ÝÝÝÝû¤¶¯´2'
    nlohmann::json nd = nlohmann::json::parse(p);       // kaboom! / Exception
    return nd;
}
Run Code Online (Sandbox Code Playgroud)

感谢帮助!

Kyl*_*yle 6

问题在这里:

ds.copy(rd.get(), ds.size() + 1);
Run Code Online (Sandbox Code Playgroud)

std::string::copy不复制空终止符,因此当您在此处构造字符串时:

std::string p = d.get(); 
Run Code Online (Sandbox Code Playgroud)

您读过数组的末尾并调用未定义的行为。这可能可以通过使用来避免std::stringstd::shared_ptr<char[]>不寻常。