1

I'm working on pset6. I'm at the part of the main.c function where I want to start combining the root and the absolute path. I was hoping to do something like this:

char* needle = NULL;
char* query = NULL;
needle = strchr(requestTarget, '?');
if (NULL == needle)
{
    query[0] = '\0';
}
else
{
    query = needle + 1;
}

The point here is to handle the case when there is no ? in the request path. I keep segmentation faulting when I try make that first if statement work, and there must be something about strings and char* and the like that I'm still not getting. When I do pass in things like /cat.jpg? HTTP/1.1 then it works fine -- my query has length 0.

Any hints would be appreciated!

1 Answer 1

1

The problem revolves around the var query.Remember first that it is a pointer, so it contains an address. Let's start with the else clause that works. If you find a ? in the string, you assign the address of the ? to needle, and then copy that address from needle to query and add 1 to that address.

The problem is in the 'then' clause of the if statement. At the point where you try to execute query[0] = '\0'; query is assigned the NULL pointer value - it doesn't point at anything. This statement tries to put something, \0, into a nonexistent memory location, causing the seg fault. Remember that query is just a pointer, not a string array.

For more info on char* x vs char array[size], etc., see the following:

different between pointers and pointer to arrays?

If this answers your question, please accept the answer to remove your question from the unanswered question pool. Let's keep up on forum maintenance. ;-)

2
  • In addition, notice that the distribution code said: char query[] = "TODO"; This should be a hint that you don't want to use a char*.
    – curiouskiwi
    Commented Jul 9, 2015 at 6:26
  • Thanks both! I ended up just setting up a temporary variable to the null terminator and pointing query to that if I didn't find the question mark.
    – Richard
    Commented Jul 9, 2015 at 13:47

You must log in to answer this question.

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