diff --git a/libavcodec/mjpeg.c b/libavcodec/mjpeg.c
index 068281d31c6f9224aeeec6a4c85cf2ea9be87f3b..874d1a7050854a18573991bf0857430310815900 100644
--- a/libavcodec/mjpeg.c
+++ b/libavcodec/mjpeg.c
@@ -1874,6 +1874,9 @@ not_the_end:
         }
     }
 the_end:
+    if(buf_ptr > buf_end)
+      buf_ptr = buf_end;
+
     dprintf("mjpeg decode frame unused %d bytes\n", buf_end - buf_ptr);
 //    return buf_end - buf_ptr;
     return buf_ptr - buf;