When the essentials you have shown in your post are run in a simple main()
program,...
int main()
{
const char* c = "GET /docs/index.html HTTP/1.1\r\n";
const char* wbeg = strchr(c, ' ') + 1; // points to '/'
const char* wend = strchr(wbeg, ' ') -1; // points to 'l'
char word[256];
strncpy(word, wbeg, wend - wbeg);
printf("%s", word);
return 0;
}
...no faults are observed in my environment. So the only suggestions, short of posting the rest of the relevant code, all center around making sure you are not invoking UB.
1) In your statement:
strncpy(word, wbeg, wend - wbeg);
`wend - wbeg` is == 15
while /docs/index.html
is 16 char long.
Change your statement to:
strncpy(word, wbeg, (wend - wbeg)+1);
2) Start with initialized variables:
char word[SIZE] = ""
3) strncpy
does not NULL terminate. If the target you are copying to has not been initialized prior to use, or you do not explicitly null terminate after using, UB can occur.
example:
char target[]; //contents of target are not guaranteed
char source[]="abcdefghijklmnopqrstuv";
strncpy(target, source, 3);
it is possible to get the following results:
|a|b|c|?|?|?|?|?|?|?|?|?|?|?|?|?|...
where ? can be anything.
If you want to guarantee that an ASCII NUL byte is at the end of the copied bytes, you can use the following:
strncpy (target, source, 3);
target[3] = 0;
|a|b|c|\0|?|?|?|?|?|?|?|?|?|?|?|?|...
4) If copying takes place between two objects that overlap, the behavior is undefined. Make sure you are checking the results of strchr()
functions before using their results in strncpy()