On Fri, Nov 12, 2010 at 7:08 PM, Trevor Burnham <[email protected]>wrote:

>  const char* stringArgToStr(const v8::Local<v8::Value> arg) {
>    v8::String::AsciiValue v8Str(arg);
>    char *cStr = (char*) malloc(strlen(*v8Str) + 1);
>    strcpy(cStr, *v8Str);
>    return cStr;
>  }
>

That _is_ a leak. You're returning a (const char *), and const is generally
a hint to the caller that the ownership lies elsewhere. The solution i've
used when i need to pass a string around is simply to wrap it in some
high-level String type like std::string:

AsciiString astr(arg);
char const * cs = *astr;
return cs ? std::string(cs) : std::string(); // string() ctor doesn't like
0.

Then there are no leaks, and from there the caller can use string.c_str() to
fetch the raw C string.

However, even then, when passing the (char const *) to C APIs, those APIs
_must not_ hold that pointer. They may consume, copy, or ignore the data
during the function call's lifetime, but not reference it directly for later
use. The reason is because the std::string (or AsciiString) holding the
bytes owns that (char const *) and will free it (or make it available for
GC) when that holder object goes out of scope.

i hope this helps.

-- 
----- stephan beal
http://wanderinghorse.net/home/stephan/

-- 
v8-users mailing list
[email protected]
http://groups.google.com/group/v8-users

Reply via email to