diff --git a/libavcodec/dpx.c b/libavcodec/dpx.c
index f75e2cbbca690fe86ec4310024e93168d3f8851a..cf23bb6ba1fc3e7521e4b8db8874ba54a047f38e 100644
--- a/libavcodec/dpx.c
+++ b/libavcodec/dpx.c
@@ -395,12 +395,14 @@ static int decode_frame(AVCodecContext *avctx,
                     if (elements == 4)
                         *dst[3]++ = read16(&buf, endian) >> shift & 0xFFF;
                 } else {
-                    *dst[2]++ = read12in32(&buf, &rgbBuffer,
-                                           &n_datum, endian);
+                    if (elements >= 3)
+                        *dst[2]++ = read12in32(&buf, &rgbBuffer,
+                                               &n_datum, endian);
                     *dst[0]++ = read12in32(&buf, &rgbBuffer,
                                            &n_datum, endian);
-                    *dst[1]++ = read12in32(&buf, &rgbBuffer,
-                                           &n_datum, endian);
+                    if (elements >= 2)
+                        *dst[1]++ = read12in32(&buf, &rgbBuffer,
+                                               &n_datum, endian);
                     if (elements == 4)
                         *dst[3]++ = read12in32(&buf, &rgbBuffer,
                                                &n_datum, endian);