Ok, to my limited understanding, when we use pointers and allocate new memory within a class, we are to create a destructor that returns memory used by that class when that class is no longer in scope.
For memory allocated to private variables contained within the class this is easy. However, what happens to the memory generated by, lets say, a function of our class which is then passed elsewhere?
/***************************************************************/
#include <iostream>
class ExampleClass{
public:
/* basic constructor */
ExampleClass():data("Hello World!"){}
/* returns data as it currently is */
constchar * getData(){ returnconst_cast<char*>(data); }
/* creates a pointer large enough to hold 'data' twice and returns it */
char * repeatData(){
// allocate memory equal to twice the size of 'data'
char * cPtr = (char*)calloc(strlen(data) * 2 + 1, sizeof(char));
strncat(cPtr, data, strlen(data) +1); // concatinate data
strncat(cPtr, data, strlen(data) +1); // concatinate data again
return cPtr;
}// end repeatData
private:
char * data;
};// end ExampleClass
/* main to test class */
int main(){
ExampleClass ec; // example of ExampleClass
char * info = ec.repeatData(); // captured the repeated 'data'
std::cout << info << std::endl; // printed to screen
free(info); info = NULL; // return memory to system
return 0;
} // end main
/***************************************************************/
Ok, question is: does the use of the function call 'repeatData' create a memory leak? At what point, if any, does the data crated in that function get returned to the system? If it's not automatically returned, would I then need to have line 32 as shown above?
Functions that return pointers should be very explicit about how the referenced memory is managed. In the case of repeatData() it is the caller's responsibility to dispose of the memory obtained for it, and should be so noted in the documentation.
BTW, never (really!) mix malloc()/free() with new/delete in your C++ programs. It is OK to use both in the same program, but not on the same variables, as you have above.