diff --git a/libavcodec/gif.c b/libavcodec/gif.c
index f373819b4f670757fb46f88690a61e4ddfaff108..66847bb783693ae7788b7d87f3ebd314005feffc 100644
--- a/libavcodec/gif.c
+++ b/libavcodec/gif.c
@@ -191,11 +191,9 @@ static av_cold int gif_encode_init(AVCodecContext *avctx)
 
     avctx->coded_frame = &s->picture;
     s->lzw = av_mallocz(ff_lzw_encode_state_size);
-    if (!s->lzw)
-        return AVERROR(ENOMEM);
     s->buf = av_malloc(avctx->width*avctx->height*2);
-    if (!s->buf)
-         return AVERROR(ENOMEM);
+    if (!s->buf || !s->lzw)
+        return AVERROR(ENOMEM);
     return 0;
 }