C++ POST request with cURL + JSON Lib
On this line:
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_data.dump().c_str());
The string object returned by dump()
is temporary and destroyed when curl_easy_setopt()
exits, thus leaving CURLOPT_POSTFIELDS
with a dangling pointer that may or may not still be pointing to the JSON data in memory by the time libCURL tries to post it.
Per the CURLOPT_POSTFIELDS
documentation:
The data pointed to is NOT copied by the library: as a consequence, it must be preserved by the calling application until the associated transfer finishes. This behaviour can be changed (so libcurl does copy the data) by setting the
CURLOPT_COPYPOSTFIELDS
option.
So, you need to either:
change
CURLOPT_POSTFIELDS
toCURLOPT_COPYPOSTFIELDS
:curl_easy_setopt(curl, CURLOPT_COPYPOSTFIELDS, json_data.dump().c_str());
save the result of
json_data.dump()
to a local variable that does not go out of scope until aftercurl_easy_perform()
exits:std::string json = json_data.dump();curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json.c_str());...