c++ - 在 X 个字符后限制 libcurl 返回

标签 c++ c libcurl

cURL 检索到的大于 5000 个字符的页面似乎导致我的应用程序出现段错误。

//Includes etc.
#include "mainheader.h"
using namespace std;
using namespace boost;

//Buffer is defined right after the includes
char buffer [5000];

//cURL result to buffer, which is declared above.
void function_pt(void *ptr, size_t size, size_t nmemb, void *stream)
{
    int n;
    n=sprintf(buffer,"%s", ptr, size, nmemb, stream);
}

//Function to check one URL
void checkurl(char* thisurl)
{
    //Start curl
    CURL *curl;
    CURLcode res;
    curl = curl_easy_init();

    if(curl)
    {
        curl_easy_setopt(curl, CURLOPT_URL, thisurl);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, function_pt);
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
    }
}

我不是 100% 确定这是否是导致段错误的原因,任何包含多个换行符的返回都可能导致段错误(尚未能够测试)。但我假设缓冲区会在 5000 个字符后自动切断返回的数据,但我想那对我来说太天真了。我怎样才能确保是这种情况?

最佳答案

你的 sprintf 行是错误的。您为格式字符串传递了太多参数。此外,您还可以使用 snprintf,它类似于 sprintf,但能够获取最大长度以防止缓冲区溢出。

关于c++ - 在 X 个字符后限制 libcurl 返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8191292/

相关文章:

c++ - 从字节流中提取字节

c++ - 从文件中读取文本的问题

c++ - 在同一个头文件中定义但在类外部的模板构造函数未被识别

c++ - WM_NEXTDLGCTL 可以与非对话框窗口一起使用吗?

c++ - C语言程序被检测为病毒

curl - 如何使用 CURLINFO_*_TIME 值估算 cURL 请求的代理连接时间?

c++ - 如何将 libcurl 与 Google Speech API 一起使用(--data-binary 或 --upload-file 的等价物是什么)?

php - 在 Ubuntu 上建立 PHP 客户端和 C 服务器之间的 TCP 套接字连接

xcode - 如何在 MacOS10.12 下安装 libcurl 并用于 Xcode?

c++ libcurl 进度回调下载不工作