diff --git a/mercurial/mpatch.c b/mercurial/mpatch.c
index 59837a16896da36d26e795881f4ba4454cb8ae41_bWVyY3VyaWFsL21wYXRjaC5j..9c5ced5276d6e7d54f7c3dadf5247b7ee98ec79c_bWVyY3VyaWFsL21wYXRjaC5j 100644
--- a/mercurial/mpatch.c
+++ b/mercurial/mpatch.c
@@ -247,8 +247,18 @@
 
 			/* insert new hunk */
 			ct = c->tail;
-			ct->start = bh->start - offset;
-			ct->end = bh->end - post;
+			ct->start = bh->start;
+			ct->end = bh->end;
+			if (!safesub(offset, &(ct->start)) ||
+			    !safesub(post, &(ct->end))) {
+				/* It was already possible to exit
+				 * this function with a return value
+				 * of NULL before the safesub()s were
+				 * added, so this should be fine. */
+				mpatch_lfree(c);
+				c = NULL;
+				goto done;
+			}
 			ct->len = bh->len;
 			ct->data = bh->data;
 			c->tail++;
@@ -259,7 +269,7 @@
 		memcpy(c->tail, a->head, sizeof(struct mpatch_frag) * lsize(a));
 		c->tail += lsize(a);
 	}
-
+done:
 	mpatch_lfree(a);
 	mpatch_lfree(b);
 	return c;