Fixed incorrect freeing of memory