Okay the previous question was answered clearly, but i found out another problem.
What if I do:
char *test(int ran){
char *ret = new char[ran];
// process...
return ret;
}
And then run it:
for(int i = 0; i < 100000000; i++){
string str = test(rand()%10000000+10000000);
// process...
// no need to delete str anymore? string destructor does it for me here?
}
So after converting the char* to string, I don't have to worry about the deleting anymore?
Edit: As answered, I have to delete[]
each new[]
call, but on my case its not possible since the pointer got lost, so the question is: how do I convert char to string properly?
Here you are not converting the char*
to a [std::]string
, but copying the char*
to a [std::]string
.
As a rule of thumb, for every new
there should be a delete
.
In this case, you'll need to store a copy of the pointer and delete
it when you're done:
char* temp = test(rand()%10000000+10000000);
string str = temp;
delete[] temp;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With