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.
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:
void somefunc()
{
staticint 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;
}
}