@@ -1725,6 +1725,8 @@ tuplesort_getdatum(Tuplesortstate *state, bool forward,
17251725bool
17261726tuplesort_skiptuples (Tuplesortstate * state ,int64 ntuples ,bool forward )
17271727{
1728+ MemoryContext oldcontext ;
1729+
17281730/*
17291731 * We don't actually support backwards skip yet, because no callers need
17301732 * it.The API is designed to allow for that later, though.
@@ -1760,18 +1762,23 @@ tuplesort_skiptuples(Tuplesortstate *state, int64 ntuples, bool forward)
17601762 * We could probably optimize these cases better, but for now it's
17611763 * not worth the trouble.
17621764 */
1765+ oldcontext = MemoryContextSwitchTo (state -> sortcontext );
17631766while (ntuples -- > 0 )
17641767{
17651768SortTuple stup ;
17661769bool should_free ;
17671770
17681771if (!tuplesort_gettuple_common (state ,forward ,
17691772& stup ,& should_free ))
1773+ {
1774+ MemoryContextSwitchTo (oldcontext );
17701775return false;
1771- if (should_free )
1776+ }
1777+ if (should_free && stup .tuple )
17721778pfree (stup .tuple );
17731779CHECK_FOR_INTERRUPTS ();
17741780}
1781+ MemoryContextSwitchTo (oldcontext );
17751782return true;
17761783
17771784default :