curl-library
Example httpcustomheader.c is showing bad practice/is buggy
Date: Wed, 5 Aug 2015 14:09:31 +0200
Hi @ all,
The libcurl examples contains an example for custom HTTP headers: httpcustomheader.c.
The example makes use of curl_slist_append like this:
struct curl_slist *chunk = NULL;
/* Remove a header curl would otherwise add by itself */
chunk = curl_slist_append(chunk, "Accept:");
/* Add a custom header */
chunk = curl_slist_append(chunk, "Another: yes");
/* Modify a header curl otherwise adds differently */
chunk = curl_slist_append(chunk, "Host: example.com");
/* Add a header with "blank" contents to the right of the colon. Note that
we're then using a semicolon in the string we pass to curl! */
chunk = curl_slist_append(chunk, "X-silly-header;");
According to the documentation of curl_slist_append a null pointer will be returned if something goes wrong:
> RETURN VALUE
>
> A null pointer is returned if anything went wrong, otherwise the new
> list pointer is returned.
The problem:
When for example the call
chunk = curl_slist_append(chunk, "Another: yes");
fails, the original list, that chunk previously pointed to, is lost. And as a consequence this leaks memory.
To make matters worse: the next call to curl_slist_append possibly creates a new list (unlikely as we are probably out of memory already, but possible).
I understand that this is a simple example. But I feel that a lot of people get started copying and pasting example code and then modify it for their needs. But code like this will likely remain unchanged.
Also showing this in a sample makes it seem like a "best practice" approach to chain the calls like this. What IMHO it is not.
For these reasons I would suggest to improve this example (and other examples if they contain similar code, I didn't check that).
Best regards,
Wolfgang Petroschka
(This is a follow-up to my post http://stackoverflow.com/questions/31827898/is-the-libcurl-example-httpcustomheader-c-buggy-showing-bad-practice-or-am-i-m on stackoverflow that I wrote in order to confirm my suspicion).
-------------------------------------------------------------------
List admin: http://cool.haxx.se/list/listinfo/curl-library
Etiquette: http://curl.haxx.se/mail/etiquette.html
Received on 2015-08-05