c++ - curl_easy_perform 在 URL 不正确时崩溃

标签 c++ multithreading curl libcurl

我在尝试使用 libcurl 下载文件时遇到问题。该程序使用多个线程,每个需要下载文件的线程都会创建一个 libcurl 句柄来处理。

当 URL 正确时,一切正常,但如果 URL 中有错误,程序就会崩溃。在 Debug模式下,如果 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++ - curl_easy_perform 在 URL 不正确时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13160290/

相关文章:

c++ - GDB 无法显示堆栈并显示 "#1 0x0000000000000000 in ?? ()"

php - 如何使用 CURL 为 Wordpress 发送数据

c# - 在结构 C# 中使用半字节

c++ - 在 C++ 中使用线程调用方法

单例作用域类方法中的 Java 线程安全

java - Gstreamer Tee/队列多流水线

java - 如何在java http请求中获取代理响应?

php - 转换 MySQL 数据库中的换行符以进行 CURL 连接

c++ - QList 中的 std::shared_ptr 在删除时不删除内容

c++ - C++线程中的段错误