fixed leaks and added free()