move null pointer detection outside loop