diff --git a/libavcodec/lzw.c b/libavcodec/lzw.c
index 873b31445bd2b418ae175a4cea63828c91a38ea7..b674d4e296bed64214bfdf9ef44b3690cbd23ade 100644
--- a/libavcodec/lzw.c
+++ b/libavcodec/lzw.c
@@ -101,9 +101,14 @@ void ff_lzw_decode_tail(LZWState *p)
     struct LZWState *s = (struct LZWState *)p;
 
     if(s->mode == FF_LZW_GIF) {
-        while(s->pbuf < s->ebuf && s->bs>0){
-            s->pbuf += s->bs;
-            s->bs = *s->pbuf++;
+        while (s->bs > 0) {
+            if (s->pbuf + s->bs >= s->ebuf) {
+                s->pbuf = s->ebuf;
+                break;
+            } else {
+                s->pbuf += s->bs;
+                s->bs = *s->pbuf++;
+            }
         }
     }else
         s->pbuf= s->ebuf;