# STR2CSTR? Malloc or not?

**URL:** <https://www.ruby-forum.com/t/str2cstr-malloc-or-not/99023>\
**Category:** Ruby\
**Created:** [July 19, 2006, 9:13pm UTC](https://www.ruby-forum.com/t/str2cstr-malloc-or-not/99023 "2006-07-19T21:13:06Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [July 19, 2006, 9:13pm UTC](https://www.ruby-forum.com/t/str2cstr-malloc-or-not/99023/1 "2006-07-19T21:13:06Z")

</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:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [July 19, 2006, 10:58pm UTC](https://www.ruby-forum.com/t/str2cstr-malloc-or-not/99023/2 "2006-07-19T22:58:54Z")

</div>

removed\_email\_address@domain.invalid wrote:

> char \* first\_string = malloc (sizeof(passed\_in\_string) + 1);  
> strcpy(first\_string, passed\_in\_string);
> 
> Thanks,
> 
> Jared  
> [http://jaredricardson.net](http://jaredricardson.net)

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.
