mpreduce: Don't crash if we've accumulated no instructions.
[u/mdw/catacomb] / mpreduce.c
index 02ce2cf..1c39564 100644 (file)
@@ -119,7 +119,7 @@ int mpreduce_create(mpreduce *r, mp *p)
        INSTR(op | !!b, w, b);
     }
   }
-  if ((DA(&iv)[DA_LEN(&iv) - 1].op & ~1u) == MPRI_SUB) {
+  if (DA_LEN(&iv) && (DA(&iv)[DA_LEN(&iv) - 1].op & ~1u) == MPRI_SUB) {
     mp_drop(r->p);
     DA_DESTROY(&iv);
     return (-1);
@@ -130,7 +130,9 @@ int mpreduce_create(mpreduce *r, mp *p)
   /* --- Wrap up --- */
 
   r->in = DA_LEN(&iv);
-  if (!r->s) {
+  if (!r->in)
+    r->iv = 0;
+  else if (!r->s) {
     r->iv = xmalloc(r->in * sizeof(mpreduce_instr));
     memcpy(r->iv, DA(&iv), r->in * sizeof(mpreduce_instr));
   } else {
@@ -167,7 +169,7 @@ int mpreduce_create(mpreduce *r, mp *p)
 void mpreduce_destroy(mpreduce *r)
 {
   mp_drop(r->p);
-  xfree(r->iv);
+  if (r->iv) xfree(r->iv);
 }
 
 /* --- @mpreduce_dump@ --- *