I have the following code that adds data to a rapidjson::Document, declared thus:
rapidjson::Document rest;
rest.SetObject();
in a loop.
Value v(value.c_str());
stringstream ss;//create a stringstream
ss << "a" << colnum;
const char* colnumstr = ss.str().c_str();
cout << "json: colnumstr = \"" << colnumstr << "\", value = \"" << value << "\"" << endl;
rest.AddMember(colnumstr,v,rest.GetAllocator());
When the loop is over I add the json as a string to a map, like so:
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
rest.Accept(writer);
string reststring = buffer.GetString();
cout << "Pushing " << reststring << " to map" << endl;
parseddata["rest"].push_back(reststring);
Heres the wierd bit:
json: colnumstr = "a1", value = "13745438"
json: colnumstr = "a2", value = "#N/A"
json: colnumstr = "a9", value = "Top 19"
Pushing {"a1":"9999\u0000438","99":"#N/A","31":"Top 19"} to map
Certain values seem to be getting changed. But I have no idea how or why.
First thing I see is this mistake (maybe not related to your problem) :
This is wrong, why :
ss.str(): Return a copy of the string instance..c_str(): Get the internal data of this stringBut the string instance is destroy the next line, before printing the result, so the colnumstr pointer is pointing to something not valid in memory. Hopefully most of the time the data are still valid… But in some case the data can be overwritten by something else.
The proper solution is to do
The
colnumstrObjwill be destroy at the end of the function and not immediately…