[BUG] [CRASH] Fix segmentation faults

Fix issues similar to #741

**Please review carefully!**