redmine 5708: Leak fixes

Diverse leak fixes from the latest round of valgrind logs, plus a compile-fix in a test.
All unit and acceptance tests pass.