Patch for bug in sprintf

All,

I discovered a bug in sprintf.c.  When a width is specified for one of

the ‘d’ field types and a positive Bignum is supplied for the argument,
the string is padded by one too few characters:

%ruby -ve 'puts “(%12d)\n(%12d)\n(%12s)” %
[9876543210,-9876543210,9876543210]'
ruby 1.6.8 (2002-12-24) [i386-freebsd4.7]
( 9876543210)
( -9876543210)
( 9876543210)

This is caused by the Bignum code decrementing the width even if there

is no sign character. The patch to fix this is:

— sprintf.c.original Thu Dec 12 03:16:44 2002
+++ sprintf.c Fri Apr 4 11:23:05 2003
@@ -436,14 +436,16 @@
if (s[0] == ‘-’) {
s++;
sc = ‘-’;

  •                    width--;
                  }
                  else if (flags & FPLUS) {
                      sc = '+';
    
  •                    width--;
                  }
                  else if (flags & FSPACE) {
                      sc = ' ';
    
  •                    width--;
                  }
    
  •               width--;
                  goto format_integer;
              }
              if (!RBIGNUM(val)->sign) {
    

    This does not appear to be fixed in the latest snapshot:

%ruby -ve 'puts “(%12d)\n(%12d)\n(%12s)” %
[9876543210,-9876543210,9876543210]'
ruby 1.8.0 (2003-04-03) [i386-freebsd4.7]
( 9876543210)
( -9876543210)
( 9876543210)

- Warren Brown

Hi,

···

In message “Patch for bug in sprintf” on 03/04/05, “Warren Brown” wkb@airmail.net writes:

I discovered a bug in sprintf.c. When a width is specified for one of
the ‘d’ field types and a positive Bignum is supplied for the argument,
the string is padded by one too few characters:

%ruby -ve ‘puts “(%12d)\n(%12d)\n(%12s)” %
[9876543210,-9876543210,9876543210]’
ruby 1.6.8 (2002-12-24) [i386-freebsd4.7]
( 9876543210)
( -9876543210)
( 9876543210)

This is caused by the Bignum code decrementing the width even if there
is no sign character. The patch to fix this is:

Thank you for finding and fixing a bug. How great the open source way.

						matz.