avw_dbase  *avdb;
        TimestampTz     current_time;
        bool            skipit = false;
+       Oid                     retval = InvalidOid;
+       MemoryContext tmpcxt,
+                                 oldcxt;
 
        /* return quickly when there are no free workers */
        LWLockAcquire(AutovacuumLock, LW_SHARED);
        }
        LWLockRelease(AutovacuumLock);
 
+       /*
+        * Create and switch to a temporary context to avoid leaking the memory
+        * allocated for the database list.
+        */
+       tmpcxt = AllocSetContextCreate(CurrentMemoryContext,
+                                                                  "Start worker tmp cxt",
+                                                                  ALLOCSET_DEFAULT_MINSIZE,
+                                                                  ALLOCSET_DEFAULT_INITSIZE,
+                                                                  ALLOCSET_DEFAULT_MAXSIZE);
+       oldcxt = MemoryContextSwitchTo(tmpcxt);
+
        /* use fresh stats */
        pgstat_clear_snapshot();
 
 
                SendPostmasterSignal(PMSIGNAL_START_AUTOVAC_WORKER);
 
-               return avdb->adw_datid;
+               retval = avdb->adw_datid;
        }
        else if (skipit)
        {
                rebuild_database_list(InvalidOid);
        }
 
-       return InvalidOid;
+       MemoryContextSwitchTo(oldcxt);
+       MemoryContextDelete(tmpcxt);
+
+       return retval;
 }
 
 /*