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.
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 );
}