libcurl/C :我什么时候可以释放 header 和 postdata 缓冲区?

libcurl/C : when can I free header and postdata buffers?

https://curl.se/libcurl/c/httpcustomheader.html 中有一个关于如何让 libcurl 设置自定义 header 的基本示例。但是在 的情况下,当 header 字符串是一个分配的字符数组 时,我不清楚何时释放它。我更喜欢 libcurl 复制我的 header 字符串,这样我可以在设置 header 后立即释放它们(而不是在 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 可以在用完后释放它的副本。

有什么见解吗?

curl_easy_setopt 的文档指出:

Strings passed to libcurl as 'char *' arguments, are copied by the library; thus the string storage associated to the pointer argument may be overwritten after curl_easy_setopt returns.

关于 CURLOPT_POSTFIELDS 内容如下:

The only exception to this rule is really CURLOPT_POSTFIELDS, but the alternative that copies the string CURLOPT_COPYPOSTFIELDS has some usage characteristics you need to read up on.

因此,如果您希望 libcurl 复制 postdata,则需要使用 CURLOPT_COPYPOSTFIELDS 相反。

上面写着:

Pass a char * as parameter, which should be the full data to post in a HTTP POST operation. It behaves as the CURLOPT_POSTFIELDS option, but the original data is instead copied by the library, allowing the application to overwrite the original data after setting this option.