I am currently working on verifying and dissecting the request line for pset6 server. I decided to make a smaller test program to explore some of the methods to extract the request, path, query, etc. I decided to use the strtok function to accomplish this.
I have all the elements teased apart correctly, and I was working on defining the root path (just using a hard coded string for the path) then concatenating that root with the path. This is when I encountered and oddity.
If I malloc "root" prior to defining "line";
int main(void)
{
root = calloc(1, sizeof(LimitRequestFields));
root = "~jharvard/dropbox/pset6/public"; //hard coding for testing
char line[80] = "GET /hello.php?name=derek HTTP/1.1"; //HC for testing
char req_seg[3][LimitRequestFields];
char* req_token = NULL;
int token_cnt = 0;
.......
the strtok function that divides my query into; path, MEME type, and query works fine.
// "req_token" is defined earlier in main and used with the initial
parsing of the request line into Method, Request, Version
// copy the request line for disection
char request[LimitRequestFields];
strcpy(request, req_seg[1]);
char req_path[LimitRequestFields];
char req_querry[LimitRequestFields] = "\0";
char* MIME = NULL;
const char q_mark[1] = "?";
// extract path
req_token = strtok(request, q_mark);
strncpy(req_path, req_token, LimitRequestFields);
// extract querry
req_token = strtok(NULL, q_mark);
if (req_token != NULL)
{
strncpy(req_querry, req_token, LimitRequestFields);
// printf("error(505)\n"); // printf for testing only
// return 1;
}
........
// working output
Method= GET
Request= /hello.php?name=derek
HTTP= HTTP/1.1
req_Path= /hello.php
Query= name=derek
MIME= php
Absolute Path= ~jharvard/dropbox/pset6/public/hello.php
However, if I malloc "root" directly after I define "line", the function fails;
int main(void);
{
char line[80] = "GET /hello.php?name=derek HTTP/1.1";
root = calloc(1, sizeof(LimitRequestFields));
root = "~jharvard/dropbox/pset6/public";
.....
// Bad Output
Method= GET
Request= /hello.php?name=derek
HTTP= HTTP/1.1
req_Path= .
Query= n
MIME=
Absolute Path= ~jharvard/dropbox/pset6/public.
In running GDB with the calloc call at the beginning of main; I discovered that the variable "request" is a valid string, however after the strtok, req_token only contains a single period (instead of the actual request).
If I move it back to the top of main, or all the way down close to where I concatenate absolute path it works fine.
If anyone understands why this occurs, could you please explain it to me? Thanks in advance for your time