diff --git a/src/backend/catalog/pg_shdepend.c b/src/backend/catalog/pg_shdepend.c
index d89a9fa2bf..68dad27afb 100644
--- a/src/backend/catalog/pg_shdepend.c
+++ b/src/backend/catalog/pg_shdepend.c
@@ -65,6 +65,7 @@
 #include "storage/lmgr.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
+#include "utils/memutils.h"
 #include "utils/syscache.h"
 
 typedef enum
@@ -1549,6 +1550,10 @@ shdepReassignOwned(List *roleids, Oid newrole)
 		while ((tuple = systable_getnext(scan)) != NULL)
 		{
 			Form_pg_shdepend sdepForm = (Form_pg_shdepend) GETSTRUCT(tuple);
+			MemoryContext cxt, oldcxt;
+
+			cxt = AllocSetContextCreate(CurrentMemoryContext, "shdepReassignOwned cxt", ALLOCSET_DEFAULT_SIZES);
+			oldcxt = MemoryContextSwitchTo(cxt);
 
 			/*
 			 * We only operate on shared objects and objects in the current
@@ -1656,6 +1661,9 @@ shdepReassignOwned(List *roleids, Oid newrole)
 			}
 			/* Make sure the next iteration will see my changes */
 			CommandCounterIncrement();
+
+			MemoryContextSwitchTo(oldcxt);
+			MemoryContextDelete(cxt);
 		}
 
 		systable_endscan(scan);
