Added dynamic memory allocation on encoding