fix potential overflow and null pointer dereference