Taurus Silver Taurus Silver - 1 year ago 143
C Question

CS50 PSET6: Parse function doesn't change pointers content

In one of my assignements I'm asked to implement a function which main role in the take a line of an HTTP request and extract from it multiple subtrings(Method, HTTP version etc).Please consider that the error function is already implemented.
Here is the function:

bool parse(const char* line, char* abs_path, char* query)
//I don't wanna deal with a const :p so I copied it into a normal string.
char *token;
char _line[strlen(line)];
strcpy(_line, line);

//Dividing the line into a Method, a request target, and a HTTP_version
char *search = " ";
token = strtok(_line, search);
char method[strlen(token)];
strcpy(method, token);
token = strtok(NULL, search);
char request_target[strlen(token)];
strcpy(request_target, token);
token = strtok(NULL, search);
char HTTP[strlen(token)];
strcpy(HTTP, token);

//Some error Handling
if (strcasecmp(method, "GET")!=0)
return false;
return false;
for (int i=0; i<strlen(request_target); i++)
return false;
if (strcasecmp(HTTP, "HTTP/1.1")!=0)
return false;

char *search2 = "?";
char* temp1 = strtok(request_target, search2);
abs_path = malloc(strlen(temp1)+1);
strcpy(abs_path, temp1);
char* temp2 = strtok(NULL, search2);
query = malloc(strlen(temp2)+1);
strcpy(query, temp2);
return true;

So the problem with this function is that it doesn't affect the content of the two pointers: abs_path and query. After debugging it I realised that inside the function the two of them get their correct values, but it's another story in the main function.

Could you please help me ?
Thanks a lot.

Answer Source

With the current function signature:

bool parse(const char* line, char* abs_path, char* query)

abs_path and query are passed by value. Changing them in the procedure has a local effect only (they are auto variables)

you have to change method params so pointers can be changed (I changed the parameter names too):

bool parse(const char* line, char** pabs_path, char** pquery)

then in the code

*pabs_path = malloc(strlen(temp1)+1);
strcpy(*pabs_path, temp1);
char* temp2 = strtok(NULL, search2);
*pquery = malloc(strlen(temp2)+1);
strcpy(*pquery, temp2);

When calling procedure:

const char* line = "some string";
char* abs_path,* query;
r = parse(line, &abs_path, &query);

and the comment of BLUEPIXY is valid: allocate 1 char more or you get an out of bounds

 char _line[strlen(line)+1]

this error is repeated throughout your code: look for [strlen( in your code, you'll see that you often forget to add 1 for the null terminator.