fixed two bugs when freeing memory