Skip to content

Commit 4d8aa99

Browse files
committed
Fix out of memory
1 parent aa2b209 commit 4d8aa99

File tree

1 file changed

+23
-9
lines changed

1 file changed

+23
-9
lines changed

ext/mbstring/mbstring.c

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3219,8 +3219,8 @@ PHP_FUNCTION(mb_levenshtein)
32193219

32203220
zend_long c0, c1, c2;
32213221

3222-
p1 = safe_emalloc(strlen_1, sizeof(zend_long), 0);
3223-
p2 = safe_emalloc(strlen_2, sizeof(zend_long), 0);
3222+
p1 = safe_emalloc(strlen_1 + 1, sizeof(zend_long), 0);
3223+
p2 = safe_emalloc(strlen_2 + 1, sizeof(zend_long), 0);
32243224

32253225
for (i2 = 0; i2 <= strlen_2; i2++) {
32263226
p1[i2] = i2 * cost_ins;
@@ -3232,29 +3232,43 @@ PHP_FUNCTION(mb_levenshtein)
32323232

32333233
while (in_len_1) {
32343234
tmp_wchar_len_1 = enc->to_wchar(&in_1, &in_len_1, wchar_buf_1, 128, &state);
3235-
ZEND_ASSERT(in_len_1 <= 128);
3235+
ZEND_ASSERT(tmp_wchar_len_1 <= 128);
32363236
tmp_wchar_len_2 = enc->to_wchar(&in_2, &in_len_2, wchar_buf_2, 128, &state);
32373237
len_2 += tmp_wchar_len_2;
3238-
ZEND_ASSERT(in_len_2 <= 128);
3238+
ZEND_ASSERT(tmp_wchar_len_2 <= 128);
32393239

32403240
for (i1 = 0; i1 < tmp_wchar_len_1; i1++) {
32413241
/* First loop that does not cross a 128 code points */
32423242
if (first) {
32433243
p2[0] = p1[0] + cost_del;
32443244
}
3245-
/* Insertion process when there is a surplus of 128 code points. */
32463245
if (tmp_wchar_len_2 == 0) {
3246+
/* Insertion process when there is a surplus of 128 code points. */
32473247
for (i2 = 0; i2 < tmp_wchar_len_1; i2++) {
3248-
c0 = p1[i2 + (len_2 - tmp_wchar_len_1)] + cost_rep;
3249-
c1 = p1[i2 + (len_2 - tmp_wchar_len_1) + 1] + cost_del;
3248+
/* for overflow */
3249+
if (len_2 < tmp_wchar_len_1) {
3250+
c0 = p1[i2] + cost_rep;
3251+
c1 = p1[i2 + 1] + cost_del;
3252+
} else {
3253+
c0 = p1[i2 + (len_2 - tmp_wchar_len_1)] + cost_rep;
3254+
c1 = p1[i2 + (len_2 - tmp_wchar_len_1) + 1] + cost_del;
3255+
}
32503256
if (c1 < c0) {
32513257
c0 = c1;
32523258
}
3253-
c2 = p2[i2 + (len_2 - tmp_wchar_len_1)] + cost_ins;
3259+
if (len_2 < tmp_wchar_len_1) {
3260+
c2 = p2[i2] + cost_ins;
3261+
} else {
3262+
c2 = p2[i2] + cost_ins;
3263+
}
32543264
if (c2 < c0) {
32553265
c0 = c2;
32563266
}
3257-
p2[i2 + (len_2 - tmp_wchar_len_1) + 1] = c0;
3267+
if (len_2 < tmp_wchar_len_1) {
3268+
p2[i2 + 1] = c0;
3269+
} else {
3270+
p2[i2 + (len_2 - tmp_wchar_len_1) + 1] = c0;
3271+
}
32583272
}
32593273
} else {
32603274
for (i2 = 0; i2 < tmp_wchar_len_2; i2++) {

0 commit comments

Comments
 (0)