fix bugs found by valgrind
Merge pull request #2508 from WalterBright/valgrind

fix bugs found by valgrind