Fix bugs discovered by Valgrind
Valgrind testing on Travis CI