From e2fa213cf571041dbd04ab0329303ffdc980678a Mon Sep 17 00:00:00 2001
From: Bram Moolenaar <Bram@vim.org>
Date: Thu, 26 May 2022 16:32:44 +0100
Subject: [PATCH] patch 8.2.5024: using freed memory with "]d"

Problem:    Using freed memory with "]d".
Solution:   Copy the pattern before searching.

---
 src/normal.c                 | 6 ++++++
 src/testdir/test_tagjump.vim | 6 ++++++
 2 files changed, 12 insertions(+)

diff --git a/src/normal.c b/src/normal.c
index e9e587d..71c05bb 100644
--- a/src/normal.c
+++ b/src/normal.c
@@ -4425,6 +4425,11 @@ nv_brackets(cmdarg_T *cap)
 	    clearop(cap->oap);
 	else
 	{
+	     // Make a copy, if the line was changed it will be freed.
+	    ptr = vim_strnsave(ptr, len);
+	    if (ptr == NULL)
+		return;
+
 	    find_pattern_in_path(ptr, 0, len, TRUE,
 		cap->count0 == 0 ? !isupper(cap->nchar) : FALSE,
 		((cap->nchar & 0xf) == ('d' & 0xf)) ?  FIND_DEFINE : FIND_ANY,
@@ -4433,6 +4438,7 @@ nv_brackets(cmdarg_T *cap)
 			    islower(cap->nchar) ? ACTION_SHOW : ACTION_GOTO,
 		cap->cmdchar == ']' ? curwin->w_cursor.lnum + 1 : (linenr_T)1,
 		(linenr_T)MAXLNUM);
+	    vim_free(ptr);
 	    curwin->w_set_curswant = TRUE;
 	}
     }
diff --git a/src/testdir/test_tagjump.vim b/src/testdir/test_tagjump.vim
index 24df68f..0eb9491 100644
--- a/src/testdir/test_tagjump.vim
+++ b/src/testdir/test_tagjump.vim
@@ -563,6 +563,12 @@ func Test_define_search()
   sil norm o0
   sil! norm 
   bwipe!
+
+  new somefile
+  call setline(1, ['first line', '', '#define something 0'])
+  sil norm 0o0
+  sil! norm ]d
+  bwipe!
 endfunc
 
 " vim: shiftwidth=2 sts=2 expandtab
-- 
2.27.0

