Fix errors found by Valgrind
Merge pull request #849 from sjinks/valgrind

[BUG] Errors found by Valgrind