STR2CSTR? Malloc or not?

J

jared.r.richardson

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
 
T

Timothy Hunter

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

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top