diff --git a/libavcodec/exr.c b/libavcodec/exr.c
index f08576af22c61b1155b9faaff71fad79531ae494..47f59bd638d7a9d383e5656d509379302b70cbd2 100644
--- a/libavcodec/exr.c
+++ b/libavcodec/exr.c
@@ -558,7 +558,7 @@ static int huf_decode(const uint64_t *hcode, const HufDec *hdecod,
     while (lc > 0) {
         const HufDec pl = hdecod[(c << (HUF_DECBITS - lc)) & HUF_DECMASK];
 
-        if (pl.len) {
+        if (pl.len && lc >= pl.len) {
             lc -= pl.len;
             get_code(pl.lit, rlc, c, lc, gb, out, oe, outb);
         } else {