fix possible buffer overflows and undefined behaviour