Fix memory leak issues reported by valgrind