Note that there are some explanatory texts on larger screens.

plurals
  1. POstrtok and memory leaks
    text
    copied!<p>I wrote a simple url parser using strtok(). here's the code</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; typedef struct { char *protocol; char *host; int port; char *path; } aUrl; void parse_url(char *url, aUrl *ret) { printf("Parsing %s\n", url); char *tmp = (char *)_strdup(url); //char *protocol, *host, *port, *path; int len = 0; // protocol agora eh por exemplo http: ou https: ret-&gt;protocol = (char *) strtok(tmp, "/"); len = strlen(ret-&gt;protocol) + 2; ret-&gt;host = (char *) strtok(NULL, "/"); len += strlen(ret-&gt;host); //printf("char at %d =&gt; %c", len, url[len]); ret-&gt;path = (char *)_strdup(&amp;url[len]); ret-&gt;path = (char *) strtok(ret-&gt;path, "#"); ret-&gt;protocol = (char *) strtok(ret-&gt;protocol, ":"); // host agora é por exemplo address.com:8080 //tmp = (char *)_strdup(host); //strtok(tmp, ":"); ret-&gt;host = (char *) strtok(ret-&gt;host, ":"); tmp = (char *) strtok(NULL, ":"); if(tmp == NULL) { if(strcmp(ret-&gt;protocol, "http") == 0) { ret-&gt;port = 80; } else if(strcmp(ret-&gt;protocol, "https") == 0) { ret-&gt;port = 443; } } else { ret-&gt;port = atoi(tmp); } //host = (char *) strtok(NULL, "/"); } /* * */ int main(int argc, char** argv) { printf("hello moto\n"); aUrl myUrl; parse_url("http://teste.com/Teste/asdf#coisa", &amp;myUrl); printf("protocol is %s\nhost is %s\nport is %d\npath is %s\n", myUrl.protocol, myUrl.host, myUrl.port, myUrl.path); return (EXIT_SUCCESS); } </code></pre> <p>As you can see, I use strtok() a lot so I can "slice" the url. I don't need to support urls different than http or https so the way it's done solves all of my problems. My concern is (this is running on an embedded device) - Am I wasting memory ? When I write something like</p> <pre><code>ret-&gt;protocol = (char *) strtok(tmp, "/"); </code></pre> <p>And then later call </p> <pre><code>ret-&gt;protocol = (char *) strtok(ret-&gt;protocol, ":"); </code></pre> <p>Does me first pointer ret->protocol held remain in memory ? I thought that maybe I should set the first call to a tmp pointer, call strtok pointing ret->protocol to the right portion of the string (the second call) and then free(tmp).</p> <p>What should be the best way to use strtok ?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload