Fixed some bugs identified by Valgrind