What happens if the Queen survives an heir (UK)?

All legal systems have rules about who gets property which becomes ownerless on the death of the present owner. In this context rights, titles, offices etc can be property just like land or cattle. These rules are generally referred to as the “law of succession” or something term like that.

In the common law world, there are common law rules, but these have been modified by statute. In some common law countries, they have codified the law of succession; that is to say, they have legislation which states comprehensively how property passes on the death of the current owner; in other countries, the common law rules still apply, subject to specific legislated modifications.

As regards successon to the crown in the UK, there is as you say legislation in place, but that legislation employs but does not define the concept of “heir”. So that’s a common law concept; common law rules applyt work out who is the “heir”, and then the statutory rules overlay that to change the outcome that would apply if just the common law rules apply. Most obviously, UK law on succession to the crown states that it must pass to the heir of Sophie, Electress of Hannover, being Protestant. So any non-Protestants who would inherit the crown under the standard common-law rules are simply skipped over.

For succession to more ordinary property, like land, say, common law rules still apply, but they are subject again to (different) statutory modifications. For example at common law, males would inherit in preference to femailes, and elder sons in preference to younger; statute has changed this, so that all sons and daughters rank equally. More importantly, statute has given property-owners the power to make wills under which they bequeath their land to people other than the heir or heirs at common law.