Segmentation fault in my parse function (at strncpy(http, http_temp, 8);). See below relevant parts of function.

Valgrind returns error of not stack'd, malloc'd or (recently) free'd but I'm copying 8 characters into a char[] of size 9 chars - what's triggering that error?

bool parse(const char* line, char* abs_path, char* query)
    char* path_all = strstr(line, " /") + 1;
    char method[path_all - line + 2];
    strncpy(method, line, path_all - line - 1);
    method[path_all - line - 1] = '\0';

    char http[9];

    char* next_element_start = strstr(path_all, " ") + 1;
    strncpy(abs_path, path_all, next_element_start - path_all - 1);
    abs_path[next_element_start - path_all] = '\0';

    strncpy(http, next_element_start, 8);
    http[8] = '\0';

    return true;

ETA: fixed - I was looking for HTTP-version at the end of request-line, basically right after it is located.


Why are you hard-coding the strncpy length to 8?

I think the Segmentation Fault is occurring because http_temp is smaller than 8, so when the program try to read beyond the length of http_temp, it produces a segmentation fault.

You should try to make that copy dynamic, so it can handle different sizes.

  • Thanks - I hard-coded the length to 8 because that is the only correct length of HTTP-version (i.e., HTTP/1.1), but you were right that the segfault was because http_temp was smaller than 8, but that's because I was looking for HTTP-version in the wrong place. See correction above.
    – L.B.
    Jan 29 '16 at 15:04

You must log in to answer this question.

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