This is a follow up from my question at: Array of strings with malloc on C++
As I have implemented Tony D solution, I have allocated memory for an array of std::string with malloc and then created the std:string for each one of the elements with new according to:
void* TP = malloc(sizeof (string) * SS);
for (int i = 0; i < SS; i++) {
new (&((string*)TP)[i]) std::string(Token[i]);
}
(Token is a vector<string> and SS an int)
I know this is not recommended, I know it is not elegant, I know there are many other solutions for this array creation and filling, but I need to do it this way
The issue I encounter now is at the array deletion. As I create each std::string separately but the allocation for the array with a malloc, in my destructor I have written:
for (int i = 0; i < SS; i++) {
delete (&((string*) TP)[i]);
}
free(TP);
But when running, the free(TP) is accusing a "double free or corruption".
By commenting the free(TP) I solve the issue for runtime (hidding the real issue), but I need to be sure all memory is released as this may cause a memory leak within the class.
So, is the deletion of each element of TP enough to free all that memory? From my understanding the malloc has allocated memory independently and it needs to be free independently from the std::string elements; but then, why do I get this error?
newormallocor similar things directly. Use RAII facilities!