remove redundant heap allocation and refactor
check snprintf for overflow
use strncat instead of strcat