malloc()
does not call the constructor of the std::string data
, it's just a C function which allocates a chunk memory of specified size and the contents is random junk.
Therefore when you subsequently assign to the string, it does not just set the value like a plain variable does -- it calls function std::string::operator=
, which tries to release any previous contents first, but that's not correct and it crashes.
You need to use C++ operator new
to create the node instead, like so:
var = new node;
As you can see, you also don't need the ugly casts anymore.