今天写了一段代码调用libcurl库的,post的数据都会变成乱码,或者少一字节后来发现实变量有效范围的问题.
错误代码:
//......
if( NULL!=pszHttpBody ){
const std::string strPostData = pszHttpBody;
if( strPostData.size() ){
ErrCode = curl_easy_setopt( m_curl, CURLOPT_POSTFIELDSIZE, strPostData.size() );
ErrCode = curl_easy_setopt( m_curl, CURLOPT_POSTFIELDS, strPostData.c_str() );
}
}
//......
ErrCode = curl_easy_perform( m_curl );
正确代码:
//......
std::string strPostData;
if( NULL!=pszHttpBody ){
strPostData = pszHttpBody;
if( strPostData.size() ){
ErrCode = curl_easy_setopt( m_curl, CURLOPT_POSTFIELDSIZE, strPostData.size() );
ErrCode = curl_easy_setopt( m_curl, CURLOPT_POSTFIELDS, strPostData.c_str() );
}
}
//......
ErrCode = curl_easy_perform( m_curl );
问题出在变量strPostData,在错误代码中,if结束变量就释放了CURLOPT_POSTFIELDS指向了一个野指针. 错误很低级,因为使用中从来没思考过curl_easy_setopt保存的是指针还是值.