From: Eric Hodel Date: 2011-02-05T05:20:51+09:00 Subject: Re: Does RSTRING_PTR() return a '\0' terminated C? On Feb 4, 2011, at 12:07 PM, Eric Wong wrote: > Iņaki Baz Castillo wrote: >> Hi, in a Ruby C extension I need to get a '\0' terminated string given >> a Ruby string. I'm just interesed in Ruby 1.9. >> >> I'm testing that RSTRING_PTR(str) does returns a '\0' terminated >> string, ot it seems so, but I'm not sure. Source code says: >> >> #define RSTRING_PTR(str) \ >> (!(RBASIC(str)->flags & RSTRING_NOEMBED) ? \ >> RSTRING(str)->as.ary : \ >> RSTRING(str)->as.heap.ptr) >> >> Honestly, no idea about what it does :) > > It's one of my favorite things about Ruby 1.9: small strings (3 words - > 1 byte) are embedded directly inside the object to avoid malloc() > overhead. > > RSTRING_PTR() checks for the embed flag, and it'll return the embedded C > string, otherwise it'll return the pointer allocated from malloc(). > > The same thing is done with RArray and RStruct, looking at the structure > definitions will be useful. > >> So, can somebody ensure me that RSTRING_PTR() returns a pointer to C >> char finished with '\0'? > > It's always '\0'-terminated in Ruby[1], it makes life much easier for > interacting with existing C functions that assume C strings (e.g. > *printf("%s"), open(), rename(), unlink(), etc...) > > [1] - unless there's a bug somewhere, or somebody hell bent on using the > extra byte :) I don't think this is true, use RSTRING_LEN with RSTRING_PTR to get the length since the string may contain embedded NULLs. If you want a safe C string use StringValueCStr(). PS: See also README.EXT section 1.3