Fix leaks and memory handling issues