First of all, quoting C11
, chapter 7.22.3.4 (emphasis mine)
The malloc
function allocates space for an object whose size is specified by size and
whose value is indeterminate.
So, the content of the memory location is indeterminate. That is the expected behaviour.
Then, the problem starts when you use the same pointer as the argument where a string is expected, i.e, the first argument of strcat()
.
Quoting chapter 7.24.3.1 (again, emphasis mine)
The strcat
function appends a copy of the string pointed to by s2
(including the
terminating null character) to the end of the string pointed to by s1
. The initial character
of s2
overwrites the null character at the end of s1
.
but, in your case, there's no guarantee of the terminating null in the target, so it causes undefined behavior.
You need to 0-initialize the memory (or, at least the first element of the memory should be a null) before doing so. You can use calloc()
which returns a pointer to already 0-initialized memory, or least, do time[0] = '\0';
.
On a different note, you can also make use of snprintf()
which removes the hassle of initial 0-filling.