Fix possible crashes. Closes #1814.