Reputation: 13
I have this problem that whenever I try to send my post_data1 by libcurls http post it says wrong password, but when I use the fixed expression in post_data2 it logs me in. And when I cout both they are the exact same string..
Can anyone tell me why they are not the same when libcurl put them in the header? Or why they differ before I send them if that is the case.
string username = "mads"; string password = "123";
stringstream tmp_s;
tmp_s << "username=" << username << "&password=" << password;
static const char * post_data1 = tmp_s.str().c_str();
static const char * post_data2 = "username=mads&password=123";
std::cout << post_data1 << std::endl; // gives username=mads&password=123
std::cout << post_data2 << std::endl; // gives username=mads&password=123
// Fill postfields
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post_data1);
// Perform the request, res will get the return code
res = curl_easy_perform(curl);
Upvotes: 1
Views: 1661
Reputation: 14623
Try to delete the static
storage specifiers, compile and run.
NOTE: even though c_str()
result is nominally temporary, it is may also be (and usually is) permanent. For a quick fix, it may work.
Upvotes: 0
Reputation: 30055
static const char * post_data1 = tmp_s.str().c_str();
Is a problem. It returns a string object and then gets a pointer to the internal string data within that object. The string then goes out of scope at the end of that line so you are left with a pointer to ... whatever happens to be in that memory next.
static std::string str = tmp_s.str();
static const char* post_data1 = str.c_str();
Might work for you.
Upvotes: 2
Reputation: 409482
When you use tmp_s.str()
you get a temporary string. You can not save a pointer to it. You have to save it to a std::string
and use that string in the call:
std::string post_data = tmp_s.str();
// Post the data
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post_data.c_str());
If (and only if) curl_easy_setopt
copies the string (and not save just the pointer) you can use tmp_s
in the call instead:
// Post the data
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, tmp_s.str().c_str());
But I don't know if the function copies the string or just saves the pointer, so the first alternative (to use a std::string
) is probably the safest bet.
Upvotes: 7