add integer overflow guards and avoid (unlimited) stack allocation