Fix a bunch of memory leaks with thanks to @Kaelima.