【问题标题】:libcurl/C : when can I free header and postdata buffers?libcurl/C:我什么时候可以释放头和后数据缓冲区?
【发布时间】:2021-06-03 23:26:28
【问题描述】:

https://curl.se/libcurl/c/httpcustomheader.html 中有一个基本示例,说明如何让 libcurl 设置自定义标头。但是在 当标头字符串是分配的字符数组的情况下,我不清楚何时释放它。我希望 libcurl 复制我的标头字符串,这样我可以在设置标头后立即释放它们(而不是在 perform() 或 cleanup() 之后)。

CURL *curl = curl_easy_init();
struct curl_slist *chunk = NULL;
char *header = malloc(50);
strcpy(header, "my-header: ABC");
chunk = curl_slist_append(chunk, myheader);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
...
curl_easy_perform(curl);
// I would prefer to free here
// because I can run this curl handle with new headers
curl_easy_cleanup(curl);
curl_slist_free_all(chunk);
// shall I free here or will it be free by above call?

我对 POSTdata 也有同样的疑问:

char *postdata = strdup("a=1&b=2");
curl_easy_setopt(curl, CURLOPT_POST, 1L);
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, strlen(postdata));
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postdata);
// can I free postdata here? << preferred
curl_easy_perform(curl);
// can I free here?
curl_easy_cleanup(curl);
// must I free here?

我希望 libcurl 复制 postdata,以便我可以在自己的时间释放它,然后 libcurl 可以在完成后释放它的副本。

有什么见解吗?

【问题讨论】:

    标签: c libcurl


    【解决方案1】:

    curl_easy_setopt 的文档指出:

    作为 'char *' 参数传递给 libcurl 的字符串由库复制;因此,在 curl_easy_setopt 返回后,与指针参数关联的字符串存储可能会被覆盖。

    关于 CURLOPT_POSTFIELDS 的内容如下:

    此规则的唯一例外是 CURLOPT_POSTFIELDS,但复制字符串 CURLOPT_COPYPOSTFIELDS 的替代方案有一些您需要阅读的使用特征。

    因此,如果您希望 libcurl 复制 postdata,您需要使用 CURLOPT_COPYPOSTFIELDS 代替。

    上面写着:

    传递一个 char * 作为参数,它应该是在 HTTP POST 操作中发布的完整数据。它的行为类似于 CURLOPT_POSTFIELDS 选项,但原始数据由库复制,允许应用程序在设置此选项后覆盖原始数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-21
      • 1970-01-01
      • 2017-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-12
      • 1970-01-01
      相关资源
      最近更新 更多