Fix integer wrap-around bug causing segmentation fault