diff --git a/src/backend/optimizer/plan/createplan.c b/src/backend/optimizer/plan/createplan.c
index e37f2933eb..0e34f881e4 100644
--- a/src/backend/optimizer/plan/createplan.c
+++ b/src/backend/optimizer/plan/createplan.c
@@ -957,14 +957,21 @@ use_physical_tlist(PlannerInfo *root, Path *path, int flags)
 
 					attno -= FirstLowInvalidHeapAttributeNumber;
 					if (bms_is_member(attno, sortgroupatts))
+					{
+						bms_free(sortgroupatts);
 						return false;
+					}
 					sortgroupatts = bms_add_member(sortgroupatts, attno);
 				}
 				else
+				{
+					bms_free(sortgroupatts);
 					return false;
+				}
 			}
 			i++;
 		}
+		bms_free(sortgroupatts);
 	}
 
 	return true;
