Browse code

Avoid VLA for lower_{needle,haystack}

John Hawthorn authored on 28/12/2019 01:33:57
Showing 1 changed files

... ...
@@ -56,6 +56,8 @@ void mat_print(score_t *mat, char name, const char *needle, const char *haystack
56 56
 }
57 57
 #endif
58 58
 
59
+#define MATCH_MAX_LEN 1024
60
+
59 61
 static void precompute_bonus(const char *haystack, score_t *match_bonus) {
60 62
 	/* Which positions are beginning of words */
61 63
 	int m = strlen(haystack);
... ...
@@ -74,6 +76,15 @@ score_t match_positions(const char *needle, const char *haystack, size_t *positi
74 76
 	int n = strlen(needle);
75 77
 	int m = strlen(haystack);
76 78
 
79
+	if (m > MATCH_MAX_LEN || n > MATCH_MAX_LEN) {
80
+		/*
81
+		 * Unreasonably large candidate: return no score
82
+		 * If it is a valid match it will still be returned, it will
83
+		 * just be ranked below any reasonably sized candidates
84
+		 */
85
+		return SCORE_MIN;
86
+	}
87
+
77 88
 	if (n == m) {
78 89
 		/* Since this method can only be called with a haystack which
79 90
 		 * matches needle. If the lengths of the strings are equal the
... ...
@@ -85,17 +96,8 @@ score_t match_positions(const char *needle, const char *haystack, size_t *positi
85 96
 		return SCORE_MAX;
86 97
 	}
87 98
 
88
-	if (m > 1024) {
89
-		/*
90
-		 * Unreasonably large candidate: return no score
91
-		 * If it is a valid match it will still be returned, it will
92
-		 * just be ranked below any reasonably sized candidates
93
-		 */
94
-		return SCORE_MIN;
95
-	}
96
-
97
-	char lower_needle[n];
98
-	char lower_haystack[m];
99
+	char lower_needle[MATCH_MAX_LEN];
100
+	char lower_haystack[MATCH_MAX_LEN];
99 101
 
100 102
 	for (int i = 0; i < n; i++)
101 103
 		lower_needle[i] = tolower(needle[i]);