Re: [RESEND PATCH] perf tools: Add levenshtein ENOMEM check

From: Paran Lee
Date: Wed Mar 15 2023 - 04:33:57 EST




23. 3. 15. 15:11에 Paran Lee 이(가) 쓴 글:
> The levenshtein algorithm requires exception handling
> when making dynamic allocations strings.

Sorry about that. I modified the code to make it behave incorrectly.

> int len1 = strlen(string1), len2 = strlen(string2);
> - int *row0 = malloc(sizeof(int) * (len2 + 1));
> - int *row1 = malloc(sizeof(int) * (len2 + 1));
> - int *row2 = malloc(sizeof(int) * (len2 + 1));
> + int *rows, *row0, *row1, *row2;
> int i, j;
>
> + rows = malloc(3 * sizeof(int) * (len2 + 1));
> + if(!rows)
> + return -ENOMEM;
> +
> + row0 = &rows[0];
> + row1 = &rows[1];
> + row2 = &rows[2];
> +
> for (j = 0; j <= len2; j++)
> row1[j] = j * a;
> for (i = 0; i < len1; i++) {
> @@ -79,9 +85,7 @@ int levenshtein(const char *string1, const char *string2,
> }
>
> i = row1[len2];
> - free(row0);
> - free(row1);
> - free(row2);
> + free(rows);
>
> return i;
> }

I'll think about it a bit more and figure out how to patch it up to make
it look better.

BR
Paran Lee