Hi.
I have a function which parses given parts from an http request send by the browser.
The first parameter is the string received from the browser, the second is the start string from where i start parsing the main string, and the separator is the end string.
For ex.:
first parameter: "GET /a/b/c/d/e/234/234/234234/45645646/dsf/saaaaa HTTP/1.1 Host: 192.168.1.102:4444"...
the second parameter is "GET /",
the third is " ".
First i calculate the start end the end positions of the searched part (strpos is a simple wrapper for strstr, with some extra logic...i can pass an offset as the third parameter, from where i start searching for the string`s position), then if start_pos and end_pos are both greater than -1, I allocate memory for the found part, and copy it to the return variable.
The problem is that sometimes the result string contains some extra characters, like when you allocate memory for a string, and it still contains some data from a previous use. The weird part is that after malloc I bzero the whole string, and still got results like:
a/b/c/d/e/234/234/234234/45645646/dsf/saaaaa - the GET received from the browser, which needs to be extracted
a/b/c/d/e/234/234/234234/45645646/dsf/saaaaaÉ - the result of the parsing
I tried to malloc just length-1 or strncpy length-1, but in this case i loose the last character.
And here is the function:
Code:
const char *parse_part(const char *buffer, const char *str, const char *separator)
{
int start_pos = strpos(buffer, str, 0)+strlen(str);
int end_pos = strpos(buffer, separator, start_pos);
int length = 0;
char *part = NULL;
if (start_pos < 1 || end_pos < 1)
{
log_error("Invalid headers received!");
return NULL;
}
length = end_pos - start_pos;
part = (char *)malloc(length);
bzero(part, length);
strncpy(part, buffer+start_pos, length);
return part;
}
Any idea is welcome.
Thanks.