I have almost completed pset 6 but am having trouble with the php part in terms of the query not going through properly to the dynamic content string. Specifically the name. I copy the query to memory but then it starts to get overwritten at some point and by the time it reaches the dynamic content, it's some garbage value. Any suggestions on how to fix my code would be much appreciated, code below:

 // Extract query from request-target
              char* check_query = strchr(request_target, '?');
              char* query = "\0";

              // If there is no "?" or anything after a "?", do the following
              if(check_query == 0 || check_query + 1 == NULL)
                        query[0] = '\0';
                        int queryLen = strlen(check_query);   
                        char querytemp[queryLen];

                        // copy query part to query[]
                        strncpy(querytemp, check_query + 1, queryLen);
                        querytemp[queryLen] = '\0';
                        query = querytemp;                       

                        int charlenToCopy = (strlen(requestTarget) - strlen(querytemp) - 1);                    
                        requestTarget = strncpy(requestTarget, requestTarget, charlenToCopy);
                        requestTarget[charlenToCopy] = '\0';

            // Concatenate root and absolute-path
            char path[strlen(root) + strlen(requestTarget)];
            strcpy(path, root);
            strcat(path, request_target);

            // Ensure path exists
            if (access(path, F_OK) != 0)
                 printf("404 Not Found\n");

            // Ensure path is executable
            if (access(path, X_OK) != 0)
                     printf("403 Forbidden\n");

            // Extract path's extension
            char* request_target2 = strchr(request_target, '\0'); 
            char extension[request_target2 - check_stop];    
            strncpy(extension, check_stop + 1, strlen(request_target2 - strlen(check_stop)));

1 Answer 1


a string is an array of characters and, in C, an array has fixed length. that is, once the length of an array is determined, it cannot change.

you are declaring the string query to be of length 1 and initializing it with the \0 character. so now, query is always gonna be of that length and, even worse, that character cannot change as well because you are using a string literal in the initialization process and string literals are read-only in C.

solution: either use a char array of some length or allocate memory on the heap using one of the malloc functions family.

You must log in to answer this question.

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