Fix problems detected by valgrind (commit 457e32a2e2a7142616ce6c732d30bb0d2fcf8172 from master).