Fix some memory issues detected by valgrind