The logistics of this have always confused me.
How do you know how big to make the volume of the wall's interior?
What happens when the city tries to grow outside the wall?
Were most cities simply built in and around enormous castle grounds, using the walls a sort of panic room?
Since walling off a city would become (quadratically?) more expensive as the city increased in size, surely it'd be cheaper just to build a ring of small towers around the city and keep them filled with soldiers?
I've written about historic urbanism, and wall-building, in several posts in the past which you might be interested in:
While I don't know if someone might have come up with a "formula" for city wall size, a common misconception about walled cities is that dense constructions were built right up against the walls. Although the city centers were certainly dense and crowded, it was common for there to be open spaces like gardens and orchards between the city walls and the inhabited center, in addition to there existing communities outside the walls.
But you seem to discount a solution for urban expansion which another poster also didn't think of: building a larger and wider ring of walls (or an extension) around the existing walls. In my own area of interest, Italian cities, there are many cases where an inner ring of old walls is contained within a larger newer ring. Of course, there could be differences across different time period and geographic areas.
If an urban community had a need to expand rapidly, local authorities could also implement a quick fix: trace a new city limit with a wooden fortification or palisade, and construct a larger wall more gradually. Between the twelfth and fourteenth centuries cities like Bologna, Milan, and Florence would do this and eventually construct multiple rings of stone walls as communities outside the old city limit grew in size and importance (although this last post is actually mostly about the constraining effects of city walls).
You might also be interested in reading about how geographic features can impact the development of city walls, and how decision-makers handle the existence of city walls when they are no longer useful.