From 2813f38e021c6e6581c0c88fcf107e41788bc835 Mon Sep 17 00:00:00 2001
From: Bram Moolenaar <Bram@vim.org>
Date: Thu, 9 Jun 2022 19:54:24 +0100
Subject: [PATCH] patch 8.2.5072: using uninitialized value and freed memory in
 spell command

Problem:    Using uninitialized value and freed memory in spell command.
Solution:   Initialize "attr".  Check for empty line early.
---
 src/spell.c                     | 10 +++++++---
 src/testdir/test_spell_utf8.vim | 15 +++++++++++++++
 2 files changed, 22 insertions(+), 3 deletions(-)

diff --git a/src/spell.c b/src/spell.c
index d8310fa..5b25950 100644
--- a/src/spell.c
+++ b/src/spell.c
@@ -1254,7 +1254,7 @@ spell_move_to(
     char_u	*line;
     char_u	*p;
     char_u	*endp;
-    hlf_T	attr;
+    hlf_T	attr = 0;
     int		len;
 #ifdef FEAT_SYN_HL
     int		has_syntax = syntax_present(wp);
@@ -1287,6 +1287,8 @@ spell_move_to(
 
     while (!got_int)
     {
+	int empty_line;
+
 	line = ml_get_buf(wp->w_buffer, lnum, FALSE);
 
 	len = (int)STRLEN(line);
@@ -1319,7 +1321,9 @@ spell_move_to(
 	}
 
 	// Copy the line into "buf" and append the start of the next line if
-	// possible.
+	// possible.  Note: this ml_get_buf() may make "line" invalid, check
+	// for empty line first.
+	empty_line = *skipwhite(line) == NUL;
 	STRCPY(buf, line);
 	if (lnum < wp->w_buffer->b_ml.ml_line_count)
 	    spell_cat_line(buf + STRLEN(buf),
@@ -1467,7 +1471,7 @@ spell_move_to(
 	    --capcol;
 
 	    // But after empty line check first word in next line
-	    if (*skipwhite(line) == NUL)
+	    if (empty_line)
 		capcol = 0;
 	}
 
diff --git a/src/testdir/test_spell_utf8.vim b/src/testdir/test_spell_utf8.vim
index 491a406..efdecdc 100644
--- a/src/testdir/test_spell_utf8.vim
+++ b/src/testdir/test_spell_utf8.vim
@@ -797,5 +797,20 @@ func Test_word_index()
   call delete('Xtmpfile')
 endfunc
 
+func Test_check_empty_line()
+  " This was using freed memory
+  enew
+  spellgood! ﬂ
+  norm z=
+  norm yy
+  sil! norm P]svc
+  norm P]s
+
+  " set 'encoding' to clear the wordt list
+  set enc=latin1
+  set enc=utf-8
+  bwipe!
+endfunc
+
 
 " vim: shiftwidth=2 sts=2 expandtab
-- 
1.8.3.1

