Index: filter/image-gif.c
===================================================================
--- filter/image-gif.c	(revision 9862)
+++ filter/image-gif.c	(working copy)
@@ -648,11 +648,13 @@
 
     if (code == max_code)
     {
-      *sp++ = firstcode;
-      code  = oldcode;
+      if (sp < (stack + 8192))
+	*sp++ = firstcode;
+
+      code = oldcode;
     }
 
-    while (code >= clear_code)
+    while (code >= clear_code && sp < (stack + 8192))
     {
       *sp++ = table[1][code];
       if (code == table[0][code])
@@ -661,9 +663,11 @@
       code = table[0][code];
     }
 
-    *sp++ = firstcode = table[1][code];
-    code  = max_code;
+    if (sp < (stack + 8192))
+      *sp++ = firstcode = table[1][code];
 
+    code = max_code;
+
     if (code < 4096)
     {
       table[0][code] = oldcode;
