Fix a series of undefined behaviours