diff --git a/src/backend/executor/tqueue.c b/src/backend/executor/tqueue.c
index ee4e03e..8e7f35e 100644
--- a/src/backend/executor/tqueue.c
+++ b/src/backend/executor/tqueue.c
@@ -230,10 +230,13 @@ TupleQueueFunnelNext(TupleQueueFunnel *funnel, bool nowait, bool *done)
 					*done = true;
 				return NULL;
 			}
-			memcpy(&funnel->queue[funnel->nextqueue],
-				   &funnel->queue[funnel->nextqueue + 1],
-				   sizeof(shm_mq_handle *)
-						* (funnel->nqueues - funnel->nextqueue));
+			if (funnel->nextqueue <= funnel->nqueues)
+				memcpy(&funnel->queue[funnel->nextqueue],
+					   &funnel->queue[funnel->nextqueue + 1],
+					   sizeof(shm_mq_handle *)
+							* (funnel->nqueues - funnel->nextqueue));
+			else
+				funnel->nextqueue = (funnel->nextqueue + 1) % funnel->nqueues;
 			if (funnel->nextqueue < waitpos)
 				--waitpos;
 		}
