strtok()을 사용하여 간단한 URL 파서를 작성했습니다. 당신이 볼 수 있듯이 나는 여기() 많은 그래서 할 수있는 "조각"의 URL strtok를를 사용하여 코드를strtok 및 메모리 누수가
#include <stdio.h>
#include <stdlib.h>
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->protocol = (char *) strtok(tmp, "/");
len = strlen(ret->protocol) + 2;
ret->host = (char *) strtok(NULL, "/");
len += strlen(ret->host);
//printf("char at %d => %c", len, url[len]);
ret->path = (char *)_strdup(&url[len]);
ret->path = (char *) strtok(ret->path, "#");
ret->protocol = (char *) strtok(ret->protocol, ":");
// host agora é por exemplo address.com:8080
//tmp = (char *)_strdup(host);
//strtok(tmp, ":");
ret->host = (char *) strtok(ret->host, ":");
tmp = (char *) strtok(NULL, ":");
if(tmp == NULL) {
if(strcmp(ret->protocol, "http") == 0) {
ret->port = 80;
} else if(strcmp(ret->protocol, "https") == 0) {
ret->port = 443;
}
} else {
ret->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", &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);
}
을합니다. http 또는 https와 다른 URL을 지원할 필요가 없으므로 모든 문제가 해결됩니다. 내 관심사가 임베디드 기기에서 실행 중입니다. 메모리를 낭비하고 있습니까? 그때
ret->protocol = (char *) strtok(tmp, "/");
그리고 같은 나중에 전화를 쓸 때 는
ret->protocol = (char *) strtok(ret->protocol, ":");
개최 나를 먼저 포인터 RET-> 프로토콜은 메모리에 남아 있습니까
? 아마 내가 tmp 포인터에 첫 번째 호출을 설정해야한다고 생각했는데 strtok이 문자열의 오른쪽 부분 (두 번째 호출)에 ret-> 프로토콜을 가리킨 다음 무료 (tmp)를 호출해야한다고 생각했습니다.strtok을 사용하는 가장 좋은 방법은 무엇입니까?
안전을 위해 모든 strtok() 이후에 NULL 결과가 있는지 확인해야합니다. 귀하의 '/'가 없을 경우를 대비하여 귀하는 불만을 제기 할 필요가 없습니다. 일부 린트 타입 도구는 이러한 유형의 것에 대해 불평해야합니다. 입력이 정확하다고 가정하지 마십시오. – KFro