Possible Duplicate:
delete heap after returning pointer
I have a class with a member function:
char* toChar();
The member function allocates memory and return a pointer to that memory …
lets say I would use it like this:
int main() {
MyClass mc = new MyClass();
char* str = mc.toChar();
return 0;
}
where should I free the memory? In the Destructor of the class or in the program like this:
int main() {
MyClass * mc = new MyClass();
char* str = mc.toChar();
// tostuff with str
delete mc;
delete[] str;
return 0;
}
If you want it to be reusable (that is, you can call it multiple times and it may return different values, maybe because the class has changed), then you should free it in the main. Otherwise it’s up to you.
But in general you should NOT use plain strings. You should change it to use
std::stringand then return that by value.