2013-03-01 26 views
1

我有這個問題,每當我嘗試通過libcurls http post發送post_data1它說錯誤密碼,但是當我在post_data2中使用固定表達式時,它會將我記入日誌中。他們是完全相同的字符串..字符串轉換爲常量字符*問題

誰能告訴我爲什麼他們不一樣時,libcurl把它們放在頭中?或者爲什麼他們在我發送之前有所不同,如果是這樣的話。

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); 
+0

你調試了你的代碼嗎? – 2013-03-01 10:22:06

+0

我已經嘗試了兩個wireshark在Eclipse中查看數據包和調試模式以查看變量,但無法自己找到錯誤。 – typ0 2013-03-01 10:28:27

+1

爲什麼wireshark?問題出在代碼中。使用valgrind(如果在Linux上)或適當的工具(在其他平臺上) – 2013-03-01 10:38:31

回答

7

當您使用tmp_s.str()你得到一個臨時字符串。你不能保存一個指針。你必須將其保存到一個std::string並使用該字符串中的呼叫:

std::string post_data = tmp_s.str(); 

// Post the data 
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post_data.c_str()); 

如果(且僅當)curl_easy_setopt副本字符串(而不是保存只是指針),可以使用tmp_s在調用來代替:

// Post the data 
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, tmp_s.str().c_str()); 

但我不知道是否該函數的字符串複製或只是保存的指針,因此第一選擇(使用std::string)可能是最安全的賭注。

+0

感謝您的快速回復!但我已經嘗試了你說的話,我仍然得到同樣的錯誤。 – typ0 2013-03-01 10:26:01

+1

,因爲他只使用字符串,他可能會完全跳過字符串流,並將其串聯到一個字符串對象中,從而避免了該問題。 – scones 2013-03-01 10:26:19

+0

@ typ0你是否在一個獨立的函數中設置了'curl_easy_perform'的位置?或者是同一個函數中的兩個調用?請製作[SSCCE](http://sscce.org/)並用它更新您的問題。 – 2013-03-01 10:29:37

2
static const char * post_data1 = tmp_s.str().c_str(); 

是一個問題。它返回一個字符串對象,然後獲取指向該對象內部字符串數據的指針。該字符串然後在該行末尾超出範圍,因此您剩下一個指向......接下來發生在該內存中的任何內容。

static std::string str = tmp_s.str(); 
static const char* post_data1 = str.c_str(); 

可以爲你工作。

+0

感謝您的回覆,這也起作用。 – typ0 2013-03-01 10:45:24

0

嘗試刪除static存儲說明符,編譯並運行。

注意:即使c_str()結果名義上是暫時的,但它也可能(通常是)永久的。爲了快速解決,它可能工作。

+0

這沒有什麼不同,但是我也發現了這個音符。謝謝你的時間。 – typ0 2013-03-01 11:11:21