I'm trying to extract the query using functions that I've already used earlier in the program successfully (strchr and strncpy), but this code only seems to work for query strings that are 4 - 10 characters -- anything outside that tacks on an extra q and, sometimes some garbage values.

Is there something about these functions that I'm fundamentally misunderstanding? such as how involved strings are terminated, or the relationship between bytes and chars when using strncpy?

Just to clarify, len3 is a variable defined by the strlen of strrchr(line, space), so it should always be equal to 9 if the user inputs HTTP/1.1.

//Extract query
int q = 'q';
char* quotes = "\"\"";

char* qbody = strchr(request, q);
int qlen; 

if (qbody != NULL)
    qlen = strlen(qbody) - len3;
    qbody = quotes;
    qlen = 3;
char query[qlen + 3]; 

strncpy(query, qbody, qlen);

1 Answer 1


I realized there were several problems with my above code, including a misunderstanding about what to do in the NULL case. But I also wasn't null-terminating query, which I think led to the appended garbage values.

I also used the ?: ternary operator to define qlen, which seemed to help.

You must log in to answer this question.

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