diff --git a/libsoup/soup-content-sniffer.c b/libsoup/soup-content-sniffer.c
index ed57e7c..d55aab5 100644
--- a/libsoup/soup-content-sniffer.c
+++ b/libsoup/soup-content-sniffer.c
@@ -279,7 +279,8 @@ sniff_unknown (SoupContentSniffer *sniffer, SoupMessage *msg,
 			int index_pattern = 0;
 			gboolean skip_row = FALSE;
 
-			while (index_stream < resource_length) {
+			while ((index_stream < resource_length) &&
+			       (index_pattern <= type_row->pattern_length)) {
 				/* Skip insignificant white space ("WS" in the spec) */
 				if (type_row->pattern[index_pattern] == ' ') {
 					if (resource[index_stream] == '\x09' ||
