Fix a number of instances of memory leakage and add test coverage.