fix bugs found by valgrind

Too bad it takes literally days to run valgrind on the test suite. It's still running, but in the meantime I fixed these it found.