shithub: puzzles

Download patch

ref: dad2f35502c611dae758915cfb6dface4a303550
parent: 095224d5711f3482d6be0ffc01621143f25c7104
author: Simon Tatham <anakin@pobox.com>
date: Thu Apr 20 10:25:22 EDT 2023

Store a size field inside the DSF type.

This permits bounds-checking of all inputs to dsf_canonify and
dsf_merge, so that any out-of-range values will provoke assertion
failure instead of undefined behaviour.

--- a/dsf.c
+++ b/dsf.c
@@ -10,6 +10,7 @@
 #include "puzzles.h"
 
 struct DSF {
+    int size;
     int *p;
 };
 
@@ -86,6 +87,7 @@
 DSF *snew_dsf(int size)
 {
     DSF *ret = snew(DSF);
+    ret->size = size;
     ret->p = snewn(size, int);
 
     dsf_init(ret, size);
@@ -125,7 +127,7 @@
 /*    fprintf(stderr, "dsf = %p\n", dsf); */
 /*    fprintf(stderr, "Canonify %2d\n", index); */
 
-    assert(index >= 0);
+    assert(0 <= index && index < dsf->size && "Overrun in edsf_canonify");
 
     /* Find the index of the canonical element of the 'equivalence class' of
      * which start_index is a member, and figure out whether start_index is the
@@ -162,6 +164,9 @@
 void edsf_merge(DSF *dsf, int v1, int v2, bool inverse)
 {
     bool i1, i2;
+
+    assert(0 <= v1 && v1 < dsf->size && "Overrun in edsf_merge");
+    assert(0 <= v2 && v2 < dsf->size && "Overrun in edsf_merge");
 
 /*    fprintf(stderr, "dsf = %p\n", dsf); */
 /*    fprintf(stderr, "Merge [%2d,%2d], %d\n", v1, v2, inverse); */