# STR2CSTR? Malloc or not?

**URL:** <https://rubytalk.org/t/str2cstr-malloc-or-not/29105>\
**Category:** ruby-talk\
**Created:** [19 July 2006 19:10 UTC](https://rubytalk.org/t/str2cstr-malloc-or-not/29105 "2006-07-19T19:10:12Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![jared.r.richardson](https://avatars.discourse-cdn.com/v4/letter/j/c2a13f/32.png) [@jared.r.richardson](https://rubytalk.org/u/jared.r.richardson)\
**Post date:** [19 July 2006 19:10 UTC](https://rubytalk.org/t/str2cstr-malloc-or-not/29105/1 "2006-07-19T19:10:12Z")

</div>

Hi all,

I've seen code examples for STR2CSTR that have mallocs and (mostly)  
those that don't. Which way is right?

Is

char \* first\_string = STR2CSTR( passed\_in\_string);

good enough or should I be running:

char \* first\_string = malloc (sizeof(passed\_in\_string) + 1);  
strcpy(first\_string, passed\_in\_string);

Thanks,

Jared  
[http://jaredricardson.net](http://jaredricardson.net)

---

<div class="post-metadata">

**Author:** ![Tim\_Hunter4](https://avatars.discourse-cdn.com/v4/letter/t/ea5d25/32.png) [@Tim\_Hunter4](https://rubytalk.org/u/Tim_Hunter4)\
**Post date:** [19 July 2006 20:58 UTC](https://rubytalk.org/t/str2cstr-malloc-or-not/29105/2 "2006-07-19T20:58:26Z")

</div>

In 1.8.4, STR2CSTR is marked "obsolete" in ruby.h. The preferred API is String\_Value\_Ptr, which just calls rb\_string\_value\_ptr in string.c. If you look at that function, all it does is return a pointer to Ruby's copy of the string in the string object.

So I would say it depends on what you want to do with the string. If you just want to look at it, then you can just use the pointer you get back from String\_Value\_Ptr. If you want to modify it without modifying Ruby's copy of it, then you should make a copy. If you want to modify the String object itself, then I'd try to use a Ruby API function to do it instead of modifying Ruby's copy directly.

> **···**
>
> jared.r.richardson@gmail.com wrote:
> 
> > Hi all,
> > 
> > I've seen code examples for STR2CSTR that have mallocs and (mostly)  
> > those that don't. Which way is right?
> > 
> > Is
> > 
> > char \* first\_string = STR2CSTR( passed\_in\_string);
> > 
> > good enough or should I be running:
> > 
> > char \* first\_string = malloc (sizeof(passed\_in\_string) + 1);  
> > strcpy(first\_string, passed\_in\_string);
> > 
> > Thanks,
> > 
> > Jared  
> > [http://jaredricardson.net](http://jaredricardson.net)
