From 8f4aba13fea361f0873b81d38ed2daa56f024912 Mon Sep 17 00:00:00 2001
From: Petter Reinholdtsen <pere@debian.org>
Date: Sun, 16 Mar 2025 18:57:23 +0100
Subject: [PATCH] Dropped to allocate memory for comments when there are none.

This avoid calling malloc(0) expecting a non-NULL pointer returned,
and make the code in oc_comment_unpack() not depend on non POSIX specified
behaviour.

Ensured comment_lengths and user_comments are NULL if there are no comments.

Thanks to Eric Lasota for noticing.

Fixes #2304
---
 lib/decinfo.c | 45 +++++++++++++++++++++++++--------------------
 1 file changed, 25 insertions(+), 20 deletions(-)

diff --git a/lib/decinfo.c b/lib/decinfo.c
index 04d3b623..0e753045 100644
--- a/lib/decinfo.c
+++ b/lib/decinfo.c
@@ -133,28 +133,33 @@ static int oc_comment_unpack(oc_pack_buf *_opb,th_comment *_tc){
     _tc->comments=0;
     return TH_EBADHEADER;
   }
-  _tc->comment_lengths=(int *)_ogg_malloc(
-   _tc->comments*sizeof(_tc->comment_lengths[0]));
-  _tc->user_comments=(char **)_ogg_malloc(
-   _tc->comments*sizeof(_tc->user_comments[0]));
-  if(_tc->comment_lengths==NULL||_tc->user_comments==NULL){
-    _tc->comments=0;
-    return TH_EFAULT;
-  }
-  for(i=0;i<_tc->comments;i++){
-    len=oc_unpack_length(_opb);
-    if(len<0||len>oc_pack_bytes_left(_opb)){
-      _tc->comments=i;
-      return TH_EBADHEADER;
-    }
-    _tc->comment_lengths[i]=len;
-    _tc->user_comments[i]=_ogg_malloc((size_t)len+1);
-    if(_tc->user_comments[i]==NULL){
-      _tc->comments=i;
+  if(0<_tc->comments){
+    _tc->comment_lengths=(int *)_ogg_malloc(
+     _tc->comments*sizeof(_tc->comment_lengths[0]));
+    _tc->user_comments=(char **)_ogg_malloc(
+     _tc->comments*sizeof(_tc->user_comments[0]));
+    if(_tc->comment_lengths==NULL||_tc->user_comments==NULL){
+      _tc->comments=0;
       return TH_EFAULT;
     }
-    oc_unpack_octets(_opb,_tc->user_comments[i],len);
-    _tc->user_comments[i][len]='\0';
+    for(i=0;i<_tc->comments;i++){
+      len=oc_unpack_length(_opb);
+      if(len<0||len>oc_pack_bytes_left(_opb)){
+        _tc->comments=i;
+        return TH_EBADHEADER;
+      }
+      _tc->comment_lengths[i]=len;
+      _tc->user_comments[i]=_ogg_malloc((size_t)len+1);
+      if(_tc->user_comments[i]==NULL){
+        _tc->comments=i;
+        return TH_EFAULT;
+      }
+      oc_unpack_octets(_opb,_tc->user_comments[i],len);
+      _tc->user_comments[i][len]='\0';
+    }
+  } else {
+    _tc->comment_lengths=NULL;
+    _tc->user_comments=NULL;
   }
   return oc_pack_bytes_left(_opb)<0?TH_EBADHEADER:0;
 }
-- 
GitLab