Fixes some memory leaks

Another attempt at fixing some memory leaks.