I’m not clear why this should fail, and why it fails where it does:
std::string* s;
s = (std::string*)malloc(sizeof(std::string) * 10);
s[0] = "string0";
s[1] = "string1";
s[2] = "string2"; //Segmentation fault
It doesn’t matter what the size of strings assigned to s[0] – s[2] are, or how much space is malloc’ed. The same thing happens with QStrings. I presume that the trouble arises from the fact that std::string contains an internal pointer, so sizeof() just returns the size of the pointer, but given that std::strings behave like values otherwise (=, ==, etc.) I don’t see why that entails failure here.
Also, for compatibility with other code I need to use C arrays here, not e.g. std::vector. And I’m looking for a general solution (that will work with QString, QDateTime, etc) if there is one. But I’d be happy just to know what’s going on.
Edit: Got a downvote… What’s wrong with this question? I did look around first for awhile (including SO), didn’t find this addressed.
You can not
mallocan array of class objects, because this function does not invoke any constructors. You just get memory filled with garbage, which you then try to reinterpret as an array of class objects.Arrays of C++ objects are allocated with
new[].As to compatibility with other code, you probably can use
std::vector, because&vec[0]gives you a pointer to the first element in a contiguous array.If you insist on using
mallocandfree, then you’ll need to manually invoke the constructor for each array item with placement new and manually invoke each destructor before freeing.