This is incorrect:
char in[5] = "hel.s";
The string takes six, not five, characters (the sixths one is for null terminator). Without it the string is unterminated, causing strlen
, strcat
, and other functions that work on terminated strings to fail with undefined behavior.
To fix, remove 5 from the declaration, and let the compiler decide on the length for you:
char in[] = "hel.s";
In addition, your use of strncpy
is invalid: it does not implicitly append null terminators
No null-character is implicitly appended at the end of destination if source is longer than num. Thus, in this case, destination shall not be considered a null terminated C string (reading it as such would overflow).
This line
strncpy(test,in,strlen(in)-2);
always produces an unterminated string, causing subsequent call of strcat
to fail. To fix this, you need to add a terminator yourself:
size_t len = strlen(in)-2;
memcpy(test, in, len); // Do not use strncpy
test[len] = '\0';