I've just written a recursive function and it dawned on me that all the variables I use within the function will remain allocated in memory until recursion breaks. If I am recursing a large number of times or allocating large amounts of memory for variables not used in the consequent recursive function call, could this lead to alot of wasteful memory use?
E.g. in the following, only vec2
is used in the following recurse and temp_int
and temp_vec
will continue to occupy memory needlessly.
int recurse(std::vector<int> arg_vec) {
int temp_int i;
std::vector<int> temp_vec;
std::vector<int> vec2;
//... do some processing with arg_vec and temp_vec and result is stored in vec2
recurse(vec2)
return if (some condition met);
}
Should I then be allocating all memory using the new commands and deleting them before the function call? Or is there some other method for dealing with this