diff --git a/libavcodec/h264dec.c b/libavcodec/h264dec.c
index faa502ed099ec5d758998d1dd599750d88bd0bfe..4d1702e114838aadf99c57c54ce271d7079770c1 100644
--- a/libavcodec/h264dec.c
+++ b/libavcodec/h264dec.c
@@ -478,7 +478,7 @@ static void flush_dpb(AVCodecContext *avctx)
 static int get_last_needed_nal(H264Context *h)
 {
     int nals_needed = 0;
-    int i;
+    int i, ret;
 
     for (i = 0; i < h->pkt.nb_nals; i++) {
         H2645NAL *nal = &h->pkt.nals[i];
@@ -496,7 +496,14 @@ static int get_last_needed_nal(H264Context *h)
         case H264_NAL_DPA:
         case H264_NAL_IDR_SLICE:
         case H264_NAL_SLICE:
-            init_get_bits(&gb, nal->data + 1, (nal->size - 1) * 8);
+            ret = init_get_bits8(&gb, nal->data + 1, nal->size - 1);
+            if (ret < 0) {
+                av_log(h->avctx, AV_LOG_ERROR, "Invalid zero-sized VCL NAL unit\n");
+                if (h->avctx->err_recognition & AV_EF_EXPLODE)
+                    return ret;
+
+                break;
+            }
             if (!get_ue_golomb(&gb))
                 nals_needed = i;
         }