Memory management in BindingType for string class

23 views
Skip to first unread message

Jeremy Friesner

unread,
Feb 25, 2025, 9:03:04 PMFeb 25
to emscripten-discuss
Hi all,

I defined a custom BindingType<> structure for my C++ String class, and it (used along with a call to _embind_register_std_string()) seems to work fine; my only concern is that its toWireType() method calls malloc(), but I don't call free() anywhere.

My question is, is this going to leak memory?  Or is there some code inside emscripten that knows to call free() on the pointer returned by toWireType()?

My code is included below, in case it's important.

-Jeremy

----

// Tell embind how to convert String <-> JavaScript string
template <> struct emscripten::internal::BindingType<String>
{
    typedef struct
    {
        size_t length;
        char data[]; // trailing data
    } * WireType;

    static WireType toWireType(const String & v, rvp::default_tag)
    {
        WireType wt = (WireType) malloc(sizeof(size_t) + v.Length());
        wt->length = v.Length();
        memcpy(wt->data, v(), v.Length());
        return wt;
    }

    static String fromWireType(WireType v) {return String(v->data, v->length);}
};
EMSCRIPTEN_BINDINGS(String) {
   emscripten::internal::_embind_register_std_string(emscripten::internal::TypeID<String>::get(), "String");
}
Reply all
Reply to author
Forward
0 new messages