where is the memory returned?

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?

Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/***************************************************************/
#include <iostream>

class ExampleClass{
public:
	/* basic constructor */
	ExampleClass():data("Hello World!"){}

	/* returns data as it currently is */
	const char * getData(){ return const_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?
Last edited on
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.

http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.3

Hope this helps.
It helps very much, thank you. That is exactly what I wanted to know.

I'll look over the link you left as well.

I'll also make a change to the above code in case anyone else skips your comment.
Topic archived. No new replies allowed.