Fix a memory leak/corruptions detected by valgrind