diff --git a/src/bin/psql/psqlscan.l b/src/bin/psql/psqlscan.l
index d32a12c..a14d6fe 100644
--- a/src/bin/psql/psqlscan.l
+++ b/src/bin/psql/psqlscan.l
@@ -1808,7 +1808,29 @@ prepare_buffer(const char *txt, int len, char **txtcopy)
 			newtxt[i] = txt[i];
 			i++;
 			while (--thislen > 0)
+			{
+				if (i >= len)
+				{
+					/*
+					 * This could happen if cur_state->encoding is
+					 * different from input file encoding.
+					 */
+					psql_error("warning: possible conflict between client encoding %s and input file encoding\n",
+							   pg_encoding_to_char(cur_state->encoding));
+					break;
+				}
 				newtxt[i++] = (char) 0xFF;
+			}
+		}
+
+		if (i != len)
+		{
+			/*
+			 * This could happen if cur_state->encoding is
+			 * different from input file encoding.
+			 */
+			psql_error("warning: possible conflict between client encoding %s and input file encoding\n",
+					   pg_encoding_to_char(cur_state->encoding));
 		}
 	}
 
