diff --git a/src/document/html/renderer.c b/src/document/html/renderer.c
index c59a3433..cba6fc13 100644
--- a/src/document/html/renderer.c
+++ b/src/document/html/renderer.c
@@ -1132,9 +1132,16 @@ justify_line(struct html_context *html_context, int y)
word_shift = (word * diff) / (spaces - 1);
new_start = word_start + word_shift;
- /* Copy the original word, without any spaces. */
- copy_chars(html_context, new_start, y, word_len,
- &line[word_start]);
+ /* Assert that the realloc_line() above
+ * allocated enough memory for the word
+ * and the preceding spaces. */
+ assert(LEN(y) >= new_start + word_len);
+ if_assert_failed continue;
+
+ /* Copy the original word, without any spaces.
+ * word_len may be 0 here. */
+ copy_screen_chars(&POS(new_start, y),
+ &line[word_start], word_len);
/* Copy the space that preceded the word,
* duplicating it as many times as necessary.
@@ -1146,10 +1153,6 @@ justify_line(struct html_context *html_context, int y)
if (word) {
int spacex;
- /* realloc_line() was called above. */
- assert(LEN(y) >= new_start);
- if_assert_failed continue;
-
for (spacex = prev_end; spacex < new_start;
++spacex) {
copy_screen_chars(&POS(spacex, y),