Fix memory issues detected by valgrind