[Nickle] nickle: Branch 'master' - 2 commits

Keith Packard keithp at keithp.com
Wed Aug 18 10:00:22 PDT 2021


 edit.c  |   13 ++++++++-----
 prng.5c |    8 +++++++-
 2 files changed, 15 insertions(+), 6 deletions(-)

New commits:
commit 48bc85955e8316e71c02aa9b1845ff8e3490266c
Author: Keith Packard <keithp at keithp.com>
Date:   Wed Aug 18 09:56:23 2021 -0700

    edit: Use asprintf when creating file editing command to avoid overflow
    
    Instead of using a fixed buffer, have asprintf allocate the required
    space.
    
    Signed-off-by: Keith Packard <keithp at keithp.com>

diff --git a/edit.c b/edit.c
index 335e448..6c7b9ad 100644
--- a/edit.c
+++ b/edit.c
@@ -23,7 +23,7 @@
 static int
 edit (char *file_name)
 {
-    char	buf[1024];
+    char	*buf;
     char	*editor;
     int		ret;
 
@@ -31,10 +31,13 @@ edit (char *file_name)
 	    editor = DEFAULT_EDITOR;
     if (!file_name)
 	file_name = "";
-    (void) sprintf (buf, "%s %s", editor, file_name);
-    IoStop ();
-    ret = system (buf);
-    IoStart ();
+    ret = asprintf (&buf, "%s %s", editor, file_name);
+    if (ret >= 0) {
+	IoStop ();
+	ret = system (buf);
+	IoStart ();
+	free(buf);
+    }
     return ret;
 }
 
commit 2a1c006f8a89f544dc99f5502c462ee71866336e
Author: Keith Packard <keithp at keithp.com>
Date:   Wed Aug 18 09:54:22 2021 -0700

    PRNG: ensure that randint returns evenly distributed values
    
    Instead of adding 32 bits to the bit width of the maximum value,
    repeatedly generate random numbers of the target bit width until the
    value returned is in range.
    
    Signed-off-by: Keith Packard <keithp at keithp.com>

diff --git a/prng.5c b/prng.5c
index 35ba924..fecf367 100644
--- a/prng.5c
+++ b/prng.5c
@@ -61,7 +61,13 @@ namespace PRNG {
      * Returns a random integer in the range 0..'n'-1 
      */
   {
-    return randbits(32 + bit_width (n)) % n;
+    int bits = bit_width(n);
+
+    for (;;) {
+      int r = randbits(bits);
+      if (r < n)
+	return r;
+    }
   }
 
   public void shuffle(&poly[*] a) 


More information about the Nickle mailing list