fix memory corruption and a minor performance improvement