简体   繁体   English

Valcurnd中仍然可以获得libcurl C ++代码的泄漏摘要

[英]Still reachable leak summary in Valgrind for libcurl c++ code

The following functions in libcurl saves a file and returns the http status code. libcurl中的以下函数保存文件并返回http状态代码。 However, when I run this using valgrind, it is reporting 0 bytes for "definitely lost", "indirectly lost", "possibly lost", but it is reporting 47448 bytes for "still reachable" . 但是,当我使用valgrind运行此程序时,它报告0字节表示“绝对丢失”,“间接丢失”,“可能丢失”,但报告47448字节表示“仍然可达” I'm trying to resolve the "still reachable" bytes. 我正在尝试解决“仍可访问”的字节。

Are there any potential memory leaks in the code below? 以下代码中是否存在潜在的内存泄漏

size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream){
    size_t written = fwrite(ptr, size, nmemb, stream);
    return written;
}

void connectAndSaveFile(char* url, char* output_file_name){
    CURL *curl;

    curl = curl_easy_init();
    if (curl)    {
        FILE *fp = fopen(output_file_name,"wb");
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
        curl_easy_perform(curl);
        curl_easy_cleanup(curl);
        fclose(fp);
    }
}

string get_http_status_code(string URL) {
    CURL *session;
    session = curl_easy_init();
    curl_easy_setopt(session, CURLOPT_URL, URL.c_str());
    curl_easy_setopt(session, CURLOPT_NOBODY, true);

    CURLcode curl_code = curl_easy_perform (session);
    long http_code = 0;
    curl_easy_getinfo (session, CURLINFO_RESPONSE_CODE, &http_code);

    curl_easy_cleanup(session);

    std::ostringstream buff;
    buff << http_code;
    return buff.str();
}
  1. "still reachable" is most frequently not actually a leak “仍然可以到达”通常不是泄漏

  2. you might get slightly less memory reachable if you use curl_global_init and curl_global_cleanup 如果使用curl_global_initcurl_global_cleanup,则可能会获得较少的内存。

The most of the code mention above uses libcurl . 上面提到的大多数代码都使用libcurl So I think we would have to look the documentation and read about API and what are the recommended steps. 因此,我认为我们必须查看文档并阅读有关API以及推荐的步骤。

However in the below method, client is passing pointer in which fwrite API is writing and returns back to the caller. 但是,在下面的方法中,客户端传递了正在写入fwrite API的指针,并返回给调用方。 This memory needs to be released in client(who would be calling this function) code once usage is complete. 使用完成后,需要在客户端(将调用此函数的代码)中释放此内存。

size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream)

However in pure C++ ways, we should use std::fstream & std::string so that we need not worry about the memory management. 但是,以纯C ++方式,我们应该使用std::fstream & std::string这样我们就不必担心内存管理。 For more informtion you may refer to following link: 有关更多信息,请参考以下链接:

https://stackoverflow.com/a/22048298/2724703 https://stackoverflow.com/a/22048298/2724703

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM