Fix memleaks reported by Valgrind