当URL不正确时,curl_easy_perform崩溃

curl_easy_perform crashes when the URL is not correct

本文关键字:easy perform 崩溃 curl URL 不正确      更新时间:2023-10-16

我尝试使用libcurl下载文件有问题。该程序可与多个线程一起使用,每个需要下载文件的线程都会创建一个libcurl句柄以使用。

当URL正确时,一切都可以正常工作,但是如果URL中存在错误,则程序崩溃。在调试模式下,如果URL不正确,则curl_easy_perform返回错误连接代码,并且程序可以工作。相反,它在发行版中崩溃。

如何解决此错误?

这是我用来下载文件的代码,无关的代码已被压制:

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是可以从中读取的有效缓冲区的指针。如果不是,则错是您的代码。

如果将适当的指针传递给(零终止)字符串,则该字符串可以是正确的URL,但是libcurl不应因为它而崩溃(据我所知,它不是)。

首先,您可以从提供它们的函数中检查所有返回代码,只是查看一切是否按照您的想象工作。

第二,卷曲是C,不是C ,它不会生成异常。

第三,如果您的C程序正在崩溃,那么所有代码都是相关的,C程序可能会以各种有趣的方式崩溃,而实际原因可能与卷发无关,或者可能是。

您的假设太多了。

迈克尔