Fix various memory leaks

This addresses various memory leaks I revealed using valgrind.