diff --git a/src/bin/psql/psqlscan.l b/src/bin/psql/psqlscan.l
index 3575f91..218d7e0 100644
--- a/src/bin/psql/psqlscan.l
+++ b/src/bin/psql/psqlscan.l
@@ -1775,7 +1775,8 @@ prepare_buffer(const char *txt, int len, char **txtcopy)
 			/* first byte should always be okay... */
 			newtxt[i] = txt[i];
 			i++;
-			while (--thislen > 0)
+			/* thislen might be greater than len, so double-check */
+			while (--thislen > 0 && i < len)
 				newtxt[i++] = (char) 0xFF;
 		}
 	}
