Fix memleaks and one potential memleak (and move a test where it might be)