The error is in the use of PG_GETARG_NUMERIC and init_var_from_num when setting up the multi-call state; init_var_from_num points at the original num's digits rather than copying them, but start_num and stop_num have just been (potentially) detoasted in the per-call context, in which case the storage will have been freed by the next call.
Oops.
Obviously this could also be fixed by not detoasting the input until after switching to the multi-call context, but it looks to me like that would be unnecessarily complex.
Suggested patch attached.
Thanks
(Is it also worth putting an explicit warning about this kind of thing in the SRF docs?)
I think yes, it will be good. The alternative is restructuring this paragraph in the SRF docs:
The memory context that is current when the SRF is called is a transient context that will be cleared between calls. This means that you do not need to call pfree on everything you allocated using palloc; it will go away anyway. However, if you want to allocate any data structures to live across calls, you need to put them somewhere else. The memory context referenced by multi_call_memory_ctx is a suitable location for any data that needs to survive until the SRF is finished running. In most cases, this means that you should switch into multi_call_memory_ctx while doing the first-call setup.
The important part "However, if you want to allocate any data structures to live across calls, you need to put them somewhere else." is buried in the docs.
But i think explicit warning is more noticeable for new developer like me.