Fix memory errors and memory leaks