Fix memory corruption bugs