This resulted in the NUL terminator being written to the end of the buffer which was not the same as the end of the string.
That in turn caused garbage bytes from malloc() to be processed.
Also change the NUL termination to be less error prone by writing the NUL immediately after the last byte copied.
This resulted in the NUL terminator being written to the end of the buffer which was not the same as the end of the string. That in turn caused garbage bytes from malloc() to be processed. Also change the NUL termination to be less error prone by writing the NUL immediately after the last byte copied.
Reproducible with the following under valgrind: