How to delete this from memory?

I have the following pointers declared dynamically within a function that uses recursion (it calls itself):

1
2
3
	List *tempList1 = new List; 
	List *tempList2 = new List;
	List *mergedList = new List;


How would I de-allocate these at the end of my program? My initial thought is to delete them at the end of the function but I'm calling it recursively so I can't do that since I need them as I get deeper into the recursion.
Try this:

1
2
3
4
5
6
7

// process...
ReturnType r = myFunction(tempList1, tempList2, mergedList); // call function recursively
delete tempList1;
delete tempList2;
delete mergedList;
return r;
when you are calling the function recursively
then you are, each time, creating three new instances of List. If you thought that you will be creating them only once then you are wrong (unless you specifically design your code to create it on the first time). You must declare them static if that is what you want to do.
You must introduce a certain condition or something like a counter to keep track of the function call.
example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void somefunc()
{
     static int Count = 0;
        //assuming you want to create them at first only.
        static List *tempList1 = new List; 
	static List *tempList2 = new List;
	static List *mergedList = new List;
       Count ++; //now increase the recursion counter
      somefunc();
      Count --;  //and nullify the increase

     if (Count == 0)
     {
       //this would mean that this is the first call
       delete tempList1, tempList2, mergedList;
     }

     
}


You can change the code to suit your needs
Topic archived. No new replies allowed.