Fixed bugs reported by valgrind