Almost every C++ libcurl example goes like this:
std::string response_string;
curl_easy_setopt(curl, CURLOPT_URL, "http://some url");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, getAnswerFunction);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response_string);
Question is why does &response_string
work where a C char*
is expected?
Also, why does response_string.c_str()
core dump if I use that instead of &response_string
?
PS The above snippet is taken from this question but most examples use the same method
Almost every C++ libcurl example goes like this:
std::string response_string;
curl_easy_setopt(curl, CURLOPT_URL, "http://some url");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, getAnswerFunction);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response_string);
Question is why does &response_string
work where a C char*
is expected?
Also, why does response_string.c_str()
core dump if I use that instead of &response_string
?
PS The above snippet is taken from this question but most examples use the same method
Share Improve this question asked Mar 15 at 1:34 JF4JF4 5242 silver badges16 bronze badges 1 |2 Answers
Reset to default 6Question is why does
&response_string
work where a Cchar*
is expected?
A C char*
is not necessarily expected. Whatever you pass is later given as an argument to the WRITEFUNCTION
. It could be char*
, FILE*
, std::string*
, or any other pointer type depending on how WRITEFUNCTION
is implemented.
Also, why does
response_string.c_str()
core dump if I use that instead of&response_string
?
Probably due to passing a char*
where a std::string*
is expected.
In the linked question, the function getAnswerFunction
interprets the parameter of the CURLOPT_WRITEDATA
function call as a pointer to an object of type std::string
. Therefore, when using this function, the address you pass must indeed point to (the start of) such an object, otherwise you will likely get a segmentation fault or some other kind of undesired behavior.
This means that if you use &response_string
, it will work, because that expression evaluates to a pointer to an object of type std::string
. But if you pass response_string.c_str()
, it is not guaranteed to work, because the address returned by the response_string.c_str()
is not guaranteed to point to (the start of) an object of type std::string
. Depending on the implementation of std::string
, it is possible address that the address returned by response_string.c_str()
is identical to the address &response_str
, especially if the implementation makes use of short string optimization. However, you should not rely on this.
curl_off_t
, depending on what the specific option expects. I did not look at C++ implementation ofcurl_easy_setopt
, but such implementation is quite possible. For example, the last formal parameter could beconst void* parameter
, and, in the implementation, it could be reinterpreted according to those options. Nothing too weird. – Sergey A Kryukov Commented Mar 15 at 1:51