Fix leaks

Fix some memory leaks that have been detected by using valgrind in the emulator.