From abd8b1b2215bbc17747e3ff2693c77fa08d4f75e Mon Sep 17 00:00:00 2001 From: Rob Landley Date: Fri, 17 Feb 2023 15:35:18 -0600 Subject: [PATCH] Fix s/// tests get skipped before realloc() allocates new string memory. (They tried to copy the unchanged data to a destination that didn't exist yet: skip copy for null pointer and defer copy to allocation time.) --- tests/sed.test | 2 ++ toys/posix/sed.c | 8 ++++++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/tests/sed.test b/tests/sed.test index fdd59404..59e80fa1 100755 --- a/tests/sed.test +++ b/tests/sed.test @@ -213,6 +213,8 @@ testing 's l loses missing newline' "sed -n 'N;l'" 'one\\ntwo$\n' '' 'one\ntwo' testing 's -z l' "sed -zn 'N;l'" 'one\\000two$\0' '' 'one\0two\0' testing 's -z l missing newline' "sed -zn 'N;l'" 'one\\000two$\0' '' 'one\0two' +testcmd 'count match' '"s/./&X/4"' '0123X45\n' '' '012345\n' + # -i with $ last line test #echo meep | sed/sed -e '1a\' -e 'huh' diff --git a/toys/posix/sed.c b/toys/posix/sed.c index 44b3062a..d75b61a8 100644 --- a/toys/posix/sed.c +++ b/toys/posix/sed.c @@ -489,7 +489,7 @@ static void sed_line(char **pline, long plen) // Zero length matches don't count immediately after a previous match if (!mlen && !zmatch) { if (rline-line == len) break; - l2[l2used++] = *rline++; + if (l2) l2[l2used++] = *rline++; zmatch++; continue; } else zmatch = 0; @@ -524,7 +524,11 @@ static void sed_line(char **pline, long plen) // Adjust allocation size of new string, copy data we know we'll keep l2l += newlen-mlen; - if ((l2l|0xfff) > l2old) l2 = xrealloc(l2, l2old = (l2l|0xfff)+1); + if ((mlen = l2l|0xfff) > l2old) { + l2 = xrealloc(l2, ++mlen); + if (l2used && !l2old) memcpy(l2, rline-l2used, l2used); + l2old = mlen; + } if (match[0].rm_so) { memcpy(l2+l2used, rline, match[0].rm_so); l2used += match[0].rm_so; -- 2.39.2