curl_easy_perform在URL不正确时崩溃 [英] curl_easy_perform crashes when the URL is not correct
问题描述
我在尝试使用 libcurl
下载文件时出现问题。该程序使用多个线程,每个需要下载文件的线程创建一个 libcurl
句柄。
I have a problem trying to download files using libcurl
. The program works with multiple threads, every thread that needs to download a file creates a libcurl
handle to work with.
当URL正确时,一切正常,但如果在URL中有错误,程序崩溃。在调试模式下,如果URL不正确 curl_easy_perform
返回错误连接代码,程序工作。
When the URL is correct everything works, but if there is a mistake in the URL the program crashes. In debug mode, if the URL is not correct curl_easy_perform
returns an error connection code and the program works. In contrast, it crashes in release.
这是一个代码,代码如下:
How could I fix this error?
我使用下载文件,不相关的代码已被拒绝:
Here is the code that I use to download the file, irrelevant code has been supressed:
LoadFileFromServer
(
string& a_sURL
)
{
string sErrorBuffer;
struct DownloadedFile updateFile = { sFilenameToWrite, // name to store the local file if succesful
NULL }; // temp buffer
CURL* pCurl = curl_easy_init();
curl_easy_setopt( pCurl, CURLOPT_URL, a_sURL.data() );
curl_easy_setopt( pCurl, CURLOPT_FOLLOWLOCATION, 1L );
curl_easy_setopt( pCurl, CURLOPT_ERRORBUFFER, sErrorBuffer );
curl_easy_setopt( pCurl, CURLOPT_WRITEFUNCTION, BufferToFile );
curl_easy_setopt( pCurl, CURLOPT_WRITEDATA, &updateFile );
curl_easy_setopt( pCurl, CURLOPT_NOPROGRESS, 0 );
curl_easy_setopt( pCurl, CURLOPT_CONNECTTIMEOUT, 5L );
CURLcode res = curl_easy_perform( pCurl );
curl_easy_cleanup( pCurl );
}
int BufferToFile
(
void * a_buffer,
size_t a_nSize,
size_t a_nMemb,
void * a_stream
)
{
struct DownloadedFile *out = ( struct DownloadedFile * ) a_stream;
if( out && !out->stream )
{
// open file for writing
if ( 0 != fopen_s( &( out->stream ), out->filename.c_str(), "wb" ) )
return -1;
if( !out->stream )
return -1; /* failure, can't open file to write */
}
return fwrite( a_buffer, a_nSize, a_nMemb, out->stream );
}
推荐答案
libcurl要求给定的URL是指向可以读取的有效缓冲区的指针。
libcurl requires that the given URL is a pointer to a valid buffer it can read from. If it isn't, the fault is in your code.
如果你传递一个适当的指针到一个(零终止)字符串,该字符串可以是一个正确的URL或者不是,但libcurl不应该崩溃因为它(和我的知识,它不)。
If you pass a proper pointer to a (zero terminated) string, that string can be a correct URL or not, but libcurl should not crash because of it (and to my knowledge it doesn't).
这篇关于curl_easy_perform在URL不正确时崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!