curl_easy_perform crashes when the URL is not corr

2019-07-01 18:26发布

问题:

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

回答1:

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.

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



回答2:

First of all you could check all the return codes from functions that supply them, Just to see if everything has worked as you assume it has.

Second, Curl is C, not C++ it doesnt generate exceptions.

Thirdly if your C program is crashing then ALL the code is relevant, C programs can crash in all sorts of interesting ways and the actual cause can be nothing whatsoever to do with Curl, or it may be.

You are making far too many assumptions.

Michael