From d45db5e9d802659e8e4ba3457c1f354fa99b18d2 Mon Sep 17 00:00:00 2001 From: Cody Peter Mello Date: Tue, 18 Sep 2018 15:20:44 -0700 Subject: [PATCH] Fix calling split() with a third argument that lives in the target array --- bugs-fixed/README | 5 +++++ bugs-fixed/split-fs-from-array.awk | 5 +++++ bugs-fixed/split-fs-from-array.ok | 1 + run.c | 10 +++++----- 4 files changed, 16 insertions(+), 5 deletions(-) create mode 100644 bugs-fixed/split-fs-from-array.awk create mode 100644 bugs-fixed/split-fs-from-array.ok diff --git a/bugs-fixed/README b/bugs-fixed/README index 222ef68..7a9e2c1 100644 --- a/bugs-fixed/README +++ b/bugs-fixed/README @@ -23,3 +23,8 @@ and also if CONVFMT changed. 7. unary-plus: Unary plus on a string constant returned the string. Instead, it should convert the value to numeric and give that value. + +X. split-fs-from-array: If the third argument to split() comes from the +array passed as the second argument, then split() would previously read +from the freed memory and possibly produce incorrect results (depending +on the system's malloc()/free() behaviour.) diff --git a/bugs-fixed/split-fs-from-array.awk b/bugs-fixed/split-fs-from-array.awk new file mode 100644 index 0000000..fce1607 --- /dev/null +++ b/bugs-fixed/split-fs-from-array.awk @@ -0,0 +1,5 @@ +BEGIN { + a[1] = "elephantie" + a[2] = "e" + print split(a[1],a,a[2]), a[2], a[3], split(a[2],a,a[2]) +} diff --git a/bugs-fixed/split-fs-from-array.ok b/bugs-fixed/split-fs-from-array.ok new file mode 100644 index 0000000..9402b94 --- /dev/null +++ b/bugs-fixed/split-fs-from-array.ok @@ -0,0 +1 @@ +4 l phanti 2 diff --git a/run.c b/run.c index 81b75da..4efa641 100644 --- a/run.c +++ b/run.c @@ -1240,8 +1240,9 @@ Cell *split(Node **a, int nnn) /* split(a[0], a[1], a[2]); a[3] is type */ { Cell *x = 0, *y, *ap; char *s, *origs; + char *fs, *origfs = NULL; int sep; - char *t, temp, num[50], *fs = 0; + char *t, temp, num[50]; int n, tempstat, arg3type; y = execute(a[0]); /* source string */ @@ -1251,7 +1252,8 @@ Cell *split(Node **a, int nnn) /* split(a[0], a[1], a[2]); a[3] is type */ fs = *FS; else if (arg3type == STRING) { /* split(str,arr,"string") */ x = execute(a[2]); - fs = getsval(x); + origfs = fs = strdup(getsval(x)); + tempfree(x); } else if (arg3type == REGEXPR) fs = "(regexpr)"; /* split(str,arr,/regexpr/) */ else @@ -1366,9 +1368,7 @@ Cell *split(Node **a, int nnn) /* split(a[0], a[1], a[2]); a[3] is type */ tempfree(ap); tempfree(y); free(origs); - if (a[2] != 0 && arg3type == STRING) { - tempfree(x); - } + free(origfs); x = gettemp(); x->tval = NUM; x->fval = n;