diff --git a/src/gzip/inflate.c b/src/gzip/inflate.c
index 5bf5b815e..6689c282d 100644
--- a/src/gzip/inflate.c
+++ b/src/gzip/inflate.c
@@ -770,8 +770,9 @@ int ZEXPORT inflate(
                 if (copy > have) copy = have;
                 if (copy) {
                     if (state->head != Z_NULL &&
-                        state->head->extra != Z_NULL) {
-                        len = state->head->extra_len - state->length;
+                        state->head->extra != Z_NULL &&
+                        (len = state->head->extra_len - state->length) <
+                            state->head->extra_max) {
                         zmemcpy(state->head->extra + len, next,
                                 len + copy > state->head->extra_max ?
                                 state->head->extra_max - len : copy);
