STR2CSTR? Malloc or not?

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

[email protected] wrote:

char * first_string = malloc (sizeof(passed_in_string) + 1);
strcpy(first_string, passed_in_string);

Thanks,

Jared
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.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs