redmine 5708: Leak fixes in core

Diverse leak fixes from the latest round of valgrind logs, plus a compile-fix in a test.
All unit and acceptance tests pass.
Probably easiest to review commit-by-commit rather than as one monolithic diff.