Bug #9173

rb_sprintf %li format specifier does not work correctly with long values and can cause Ruby to crash

Added by Brad Sumersford over 1 year ago. Updated over 1 year ago.

[ruby-core:<unknown>]
Status:Rejected
Priority:Low
Assignee:-
ruby -v:ruby 2.0.0p195 Backport:1.9.3: UNKNOWN, 2.0.0: UNKNOWN

Description

There is additional handling of %i versus %d in BSD_vfprintf (>= 2.0). When l (long) is specified as the length, %li, the additional handling is triggered.
Note: %ld works fine, %li and %ld work in Ruby 1.9.3

Sample Code:

sprintf_test.c

#include "ruby.h"

static VALUE
sprintfTest(VALUE module, VALUE fix) {
Check_Type(fix, T_FIXNUM);

long long_value = FIX2LONG(fix);
VALUE back_to_ruby = LONG2FIX(long_value);

printf("This should show the correct value: %li\n", long_value);
rb_funcall(rb_mKernel, rb_intern("puts"), 2, rb_str_new2("This should also show the correct value: "), back_to_ruby);

return rb_sprintf("This will return the wrong value, or crash: %li", long_value);
}

void Init_sprintf() {
rb_define_method(rb_mKernel, "sprintf_test", sprintfTest, 1);

}

irb

require './sprintf'

irb(main):004:0> sprintf_test 3
This should show the correct value: 3
This should also show the correct value:
3
=> "This will return the wrong value, or crash: 1"

irb(main):004:0> sprintf_test 3
This should show the correct value: 3
This should also show the correct value:
3

irb(main):004:0> sprintf_test 4
This should show the correct value: 4
This should also show the correct value:
4
(irb):4: [BUG] Segmentation fault
ruby 2.0.0p195 (2013-05-14) [x86_64-darwin10.8.0]

History

#1 Updated by Jeremy Evans over 1 year ago

This is now expected behavior. %i starting in 2.0 means you need to provide a ruby object (VALUE) argument, not an integer. You need to switch from %li to %ld.

#2 Updated by Brad Sumersford over 1 year ago

I was trying to find confirmation of the change before posting this issue but I was unable to find a reference. Thank-you for clarifying, this can be closed.

#3 Updated by Nobuyoshi Nakada over 1 year ago

  • Status changed from Open to Rejected

Also available in: Atom PDF