diff --git a/libavcodec/j2kdec.c b/libavcodec/j2kdec.c
index b2624f9f6208c9e602869f87baadfaaa184e23d6..c712eb30e06703eec222c8f48e91c91588417cfb 100644
--- a/libavcodec/j2kdec.c
+++ b/libavcodec/j2kdec.c
@@ -167,6 +167,9 @@ static int tag_tree_decode(J2kDecoderContext *s, J2kTgtNode *node, int threshold
     J2kTgtNode *stack[30];
     int sp = -1, curval = 0;
 
+    if(!node)
+        return AVERROR(EINVAL);
+
     while(node && !node->vis){
         stack[++sp] = node;
         node = node->parent;