You should use snprintf(str, SIZE_OF_STR). This way you would make sure to not overwrite anything.

At the moment, I believe you are overwriting the memory that was allocated by the first malloc. Trouble will come soon!