diff --git a/parserInternals.c b/parserInternals.c
index 2b8646c..482d74d 100644
--- a/parserInternals.c
+++ b/parserInternals.c
@@ -36,6 +36,7 @@
 #include <zlib.h>
 #endif
 
+#include <assert.h>
 #include <libxml/xmlmemory.h>
 #include <libxml/tree.h>
 #include <libxml/parser.h>
@@ -55,6 +56,10 @@
 #include <libxml/globals.h>
 #include <libxml/chvalid.h>
 
+#define CUR(ctxt) ctxt->input->cur
+#define END(ctxt) ctxt->input->end
+#define VALID_CTXT(ctxt) (CUR(ctxt) <= END(ctxt))
+
 #include "buf.h"
 #include "enc.h"
 
@@ -422,18 +427,16 @@ xmlNextChar(xmlParserCtxtPtr ctxt)
         (ctxt->input == NULL))
         return;
 
-    if (ctxt->charset == XML_CHAR_ENCODING_UTF8) {
+    assert(VALID_CTXT(ctxt));
+
     if ((*ctxt->input->cur == 0) &&
-            (xmlParserInputGrow(ctxt->input, INPUT_CHUNK) <= 0) &&
-            (ctxt->instate != XML_PARSER_COMMENT)) {
-            /*
-             * If we are at the end of the current entity and
-             * the context allows it, we pop consumed entities
-             * automatically.
-             * the auto closing should be blocked in other cases
-             */
+        (xmlParserInputGrow(ctxt->input, INPUT_CHUNK) <= 0)) {
+        if ((ctxt->instate != XML_PARSER_COMMENT))
             xmlPopInput(ctxt);
-        } else {
+        return;
+    }
+
+    if (ctxt->charset == XML_CHAR_ENCODING_UTF8) {
         const unsigned char *cur;
         unsigned char c;
 
@@ -518,7 +521,6 @@ xmlNextChar(xmlParserCtxtPtr ctxt)
         ctxt->nbChars++;
         if (*ctxt->input->cur == 0)
             xmlParserInputGrow(ctxt->input, INPUT_CHUNK);
-        }
     } else {
         /*
          * Assume it's a fixed length encoding (1) with
