Why not just move the flag assignment to below the if (p != NULL)  check?