The error you're getting is due to
strncpy (head->word, word, strlen(word));
and
strncpy (head->sharp->word, word, strlen(word));
not terminating their targets with NUL characters. strncpy()
does not always NUL-terminate its output string; Indeed, it will only do so if word
is shorter (in # of characters) than strncpy()
's size-argument.
Therefore, at run-time and with your current source string and size-argument to strncpy()
(where the number of characters in the word is precisely equal to and not shorter than the size-argument), a NUL character is not written by strncpy()
at the end of head->word
. But when printf
tries to print your string, it must implicitly find the end of that string, marked by its terminating NUL character. So it reads through all of the buffer you allocated failing to find a NUL character, and purely by luck finds one right after the end of the buffer, thus not crashing. Nevertheless this is an invalid read; Valgrind found it for you, but you must fix it.
To fix it, I suggest that you replace the size-argument of strncpy()
with MAX_LEN-1
, and that you manually terminate the string copy with head->word[MAX_LEN-1] = '\0'
.
Alternately you can do as I have done before and implement yourself a strzcpy(char* d, char* s, size_t len)
function that copies len-1
characters and NUL-terminates. It is a shame that such a function wasn't standardized until C11.