--- wv-clean/chp.c	2009-09-01 16:38:30.000000000 +0800
+++ wv-fix2/chp.c	2026-11-05 12:19:24.195190121 +0800
@@ -520,12 +520,13 @@
     Node *testn, *testp;
     U16 i = 0, j;
     U16 sprm;
-    U8 len = 0;
+    size_t total = 0;
     U8 temp;
     Node *test = NULL;
 
     U8 *pointer, *dpointer;
     U8 *grpprl = NULL;
+    size_t left;
 
     /*
        use a binary tree ala the wmf stuff and first insert every dest sprm into it,
@@ -545,7 +546,7 @@
 	  pointer += temp;
 	  i += 2;
 	  if (test)
-	      len += temp + 2;
+	      total += temp + 2;
       }
 
     i = 0;
@@ -565,14 +566,16 @@
 	  pointer += temp;
 	  wvTrace (("p dis is %d\n", pointer - src->upx.chpx.grpprl));
 	  if (test)
-	      len += temp + 2;
+	      total += temp + 2;
       }
 
-    if (len != 0)
-	grpprl = (U8 *) wvMalloc (len);
+    if (total != 0)
+	grpprl = (U8 *) wvMalloc (total);
     else
 	return;
 
+    left = total;
+
 
     dpointer = grpprl;
 
@@ -589,7 +592,7 @@
 	  wvTrace (("i is now %d\n", i));
 
 	  pointer = (U8 *) testn->Data;
-	  for (j = 0; j < i + 2; j++)
+	  for (j = 0; j < i + 2 && left > 0; j++, left--)
 	      *dpointer++ = *pointer++;
 
 	  testp = NextNode (&tree, testn);
@@ -598,7 +601,7 @@
       }
     wvFree (dest->grpprl);
     dest->grpprl = grpprl;
-    dest->cbGrpprl = len;
+    dest->cbGrpprl = (U8) (total > 0xff ? 0xff : total);
 
     /*test */
     i = 0;
@@ -611,7 +614,7 @@
 	  pointer += temp;
 	  i += 2;
 	  if (test)
-	      len += temp + 2;
+	      total += temp + 2;
       }
 }
 

