0

I can't figure out what is wrong with my code, and I don't know where the issue is. I have tried to figure it out by putting printf calls everywhere, and it appears that my parse function works as intended, because printing out abs_path right before the return true at the end of the function gives me a correct path, i.e. / for the homepage.

However, right after that (before the urldecode function), abs_path gets reset to nothing (i.e. ""), resulting in an endless redirect, because urldecode gets passed an empty string and wants to redirect to /, which then again becomes an empty string when it gets passed into urldecode.

if (parse(line, abs_path, query)) // printf call inside of parse prints "/"
{
    // debug
    printf("abs_path before urldecode = %s\n", abs_path); // prints ""

This is my parse function (just the last few lines):

bool parse(const char* line, char* abs_path, char* query)
{
    // code that implements parse

    // debug
    printf("abs_path before return true = %s\n", abs_path); // prints "/"
    return true;
}

Does anyone have any idea what could be causing this?

3
  • make sure your string variables are big enough to hold their values and that they are terminated with a null character!
    – kzidane
    Commented Jan 17, 2016 at 10:40
  • Ah yes, that was the problem.
    – jiewpeng
    Commented Jan 17, 2016 at 11:00
  • 2
    Possible duplicate of pset6 can not return abs_path correctly Commented Feb 21, 2017 at 12:35

1 Answer 1

0

Sorry I was busy the past few days and did not provide a satisfactory answer to my own question after I solved it following Kareem's comment.

Here's my code (it's probably not the best way to do it). The problem comes in the "no query" portion of my code.

bool parse(const char* line, char* abs_path, char* query)
{
    // find spaces
    char* firstspace = strchr(line, ' ');
    char* lastspace = strrchr(line, ' ');

    // get lengths of method and request
    size_t length_line = strlen(line);
    size_t length_method = length_line - strlen(firstspace);
    size_t length_request = length_line - strlen(lastspace) - length_method - 1;

    // extract method and request target
    char method[length_method + 1];
    char request[length_request + 1];
    strncpy(method, line, length_method);
    method[length_method] = '\0';
    strncpy(request, firstspace + 1, length_request);
    request[length_request] = '\0';

    // init variables
    size_t path_length;
    size_t query_length;

    // query exists     

    // no query
    else if (!strchr(request, '?'))
    {
        query = "";
        abs_path = request;
    }

    // more code

}

I should have used strcpy(abs_path, request) instead of abs_path = request.

1
  • probably you should provide a more detailed answer for future reference!
    – kzidane
    Commented Jan 17, 2016 at 12:30

You must log in to answer this question.

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