Fix segmentation fault / undefined behaviour