Fix a memory leak and a memory corruption