@cryptotaxi247 / netdata-1 / commits / 904ff0e36

Try to shrink the buffer used on url_encode().

Frederico Lamberti Pissarra committed May 9, 2016 at 00:23 UTC 904ff0e36c2d5589a54332d807474406cafd163d
1 file changed +18 -10
src/url.c
+18 -10
@@ -27,28 +27,36 @@ char to_hex(char code) {
27 /* Returns a url-encoded version of str */
28 /* IMPORTANT: be sure to free() the returned string after use */
29 char *url_encode(char *str) {
30 - char *pstr = str,
31 - *buf = malloc(strlen(str) * 3 + 1),
32 - *pbuf = buf;
30 + char *buf, *pbuf;
31 +
32 + pbuf = buf = malloc(strlen(str) * 3 + 1);
33
34 if(!buf)
35 fatal("Cannot allocate memory.");
36
37 - while (*pstr) {
38 - if (isalnum(*pstr) || *pstr == '-' || *pstr == '_' || *pstr == '.' || *pstr == '~')
39 - *pbuf++ = *pstr;
37 + while (*str) {
38 + if (isalnum(*str) || *str == '-' || *str == '_' || *str == '.' || *str == '~')
39 + *pbuf++ = *str;
40
41 - else if (*pstr == ' ')
41 + else if (*str == ' ')
42 *pbuf++ = '+';
43
44 else
45 - *pbuf++ = '%', *pbuf++ = to_hex(*pstr >> 4), *pbuf++ = to_hex(*pstr & 15);
45 + *pbuf++ = '%', *pbuf++ = to_hex(*str >> 4), *pbuf++ = to_hex(*str & 15);
46
47 - pstr++;
47 + str++;
48 }
49 -
49 *pbuf = '\0';
50
51 + // FIX: I think this is prudent. URLs can be as long as 2 KiB or more.
52 + // We allocated 3 times more space to accomodate %NN encoding of
53 + // non ASCII chars. If URL has none of these kind of chars we will
54 + // end up with a big unused buffer.
55 + //
56 + // Try to shrink the buffer...
57 + if (!!(pbuf = (char *)realloc(buf, strlen(buf)+1)))
58 + buf = pbuf;
59 +
60 return buf;
61 }
62