# Creating new Ruby strings in C

**URL:** <https://rubytalk.org/t/creating-new-ruby-strings-in-c/9234>\
**Category:** ruby-talk\
**Created:** [6 December 2003 19:11 UTC](https://rubytalk.org/t/creating-new-ruby-strings-in-c/9234 "2003-12-06T19:11:44Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Charles\_Mills](https://avatars.discourse-cdn.com/v4/letter/c/b77776/32.png) [@Charles\_Mills](https://rubytalk.org/u/Charles_Mills)\
**Post date:** [6 December 2003 19:11 UTC](https://rubytalk.org/t/creating-new-ruby-strings-in-c/9234/1 "2003-12-06T19:11:44Z")

</div>

Some questions about the rb\_str\_new…rb\_str\_new5 functions.  
Is it possible for RSTRING(str)-\>ptr to reference a C string or part of a  
C buffer with out eventually calling free on ptr (and without stopping  
the gc)?  
I imagine the gc will eventually call free on ptr for any Ruby string  
created with rb\_str\_new2.  
What are str\_new3 and str\_new4 used for?  
Thanks in advance,  
Charlie

---

<div class="post-metadata">

**Author:** ![ts1](https://avatars.discourse-cdn.com/v4/letter/t/a8b319/32.png) [@ts1](https://rubytalk.org/u/ts1)\
**Post date:** [7 December 2003 11:56 UTC](https://rubytalk.org/t/creating-new-ruby-strings-in-c/9234/2 "2003-12-07T11:56:50Z")

</div>

> Is it possible for RSTRING(str)-\>ptr to reference a C string or part of a  
> C buffer with out eventually calling free on ptr (and without stopping  
> the gc)?

yes, and no : see mmap

mmap can be seen as a delegator : in some case, it just create a String  
object and call the corresponding String method, but it's very carefull  
about the gc

> What are str\_new3 and str\_new4 used for?

shared string used for example in string and regexp. Just an example with  
regexp

&nbsp;&nbsp;&nbsp;a = "aaa"  
&nbsp;&nbsp;&nbsp;/.\*/ =~ a  
&nbsp;&nbsp;&nbsp;a \<\< "b"

After the match, $~ and `a' "share" internally the same string, but the  
variable `a' is marked "copy-on-write". When ruby want to modify `a', it  
first duplicate the string and make the modification.

Guy Decoux

---

<div class="post-metadata">

**Author:** ![ts1](https://avatars.discourse-cdn.com/v4/letter/t/a8b319/32.png) [@ts1](https://rubytalk.org/u/ts1)\
**Post date:** [7 December 2003 11:59 UTC](https://rubytalk.org/t/creating-new-ruby-strings-in-c/9234/3 "2003-12-07T11:59:03Z")

</div>

> shared string used for example in string and regexp. Just an example with

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;^^^^^^  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;hash

> regexp

sorry,

Guy Decoux
