0

Currently working on Pset6 and I can't seem to get the parse function to work. I haven't fully implemented the function but requesting the home page should work. I was wondering if someone could help take a look at my code and point me in the right direction.

bool parse(const char* line, char* abs_path, char* query)
{
    //TODO
    char* method = malloc(5);
    strncpy(method, line, 4);
    //check that method is GET
    if (strcmp(method, "GET ") != 0)
    {
        error(405);
        return false;
    }

    //check if 4th place in line is a slash
    if (line[4] != '/')
    {
        error(501);
        return false;
    }

    char* sla = strchr(line, '/');
    char* ques = strchr(line, '?');
    char* _http = strstr(line, "HTTP");

    //if there is a question mark
    if (ques != NULL)
    {
        //copy the string from sla to the question mark
        strncpy(abs_path, sla, ques - sla);
        //if there is no query substring
        if ((_http - ques) == 2)
        {
            query = malloc(1);
            *query = '\0';
        }
        else 
        {
            query = malloc(_http - ques - 1);
            strncpy(query, ques + 1, _http - ques - 2);
        }
    }

    //no question mark
    else
    {
        abs_path = malloc(_http - sla);
        strncpy(abs_path, sla, _http - sla - 1);
    }

    char* tquo = strchr(abs_path, '\"');
    if (tquo != NULL)
    {
        error(400);
        return false;
    }

    char* _https = NULL;
    _https = malloc(9);
    strncpy(_https, _http, 8);
    if (strcmp(_https, "HTTP/1.1") != 0)
    {
        error(505);
        return false;
    }
    return true;
}

BTW I haven't added the checks for spaces in the request-target or two spaces before HTTP/1.1 yet

Thanks!

1

Scope. Pointers. When you do this abs_path = malloc(_http - sla);, you are giving a new address to the local abs_path. When you return to main, it will be looking in the "old neighborhood", ie the abs_path address from the original declaration here char abs_path[LimitRequestLine + 1];

1
  • Yup I suspected this was the issue, should I just dereference abs_path and put a string there then? How would you go about doing that?
    – Chris Shi
    Aug 8 '16 at 16:29
0

Found the solution to my problem. If I omitted the malloc line, the original pointer would not be rewritten and I can strcpy into abs_path and query. Thanks for the help!

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .