edit: I changed the example and tried to clarify what I'm doing.
I have a recursive function that takes a pointer to an array as an argument, creates a pointer to a smaller array, and calls itself, passing the smaller array as an argument
int ListOfNumbers::recursiveQuickselect(int *array, int arrayLen){
if(arrayLen > 10){
int *tempArray;
tempArray = new int[some value];
...edit tempArray....
return recursiveQuickselect(tempArray, tempArrayLen);
}
else{
//base case:
sort this small array and return an element from it
}
When I run valgrind I am told that 1 block is lost in the function recursiveQuickselect.
where do I delete tempArray in this code?
If I delete it before the call then I'm passing nothing into the function
I obviously can't delete it after the return statement.
NOTE: I cannot use vectors, this is a school assignment that does not allow them.
You want to pass the address of a dynamically sized array to a function, but want automatic cleanup of the dynamic memory since you have no way to delete the memory. Like many commented, that's exactly what std::vector
does, eg in your example
ListOfNumbers::medianOfFivePivot(int *array, int arrayLen){
std::vector<int> tempArray(tempArrayLen);
// ...edit tempArray....
return getMedian(&tempArray[0], tempArrayLen);
How about you delete
the memory in getMedian
? If getMedian
is recursive, just delete in the base case.
Or (@Havenard), you can store the value of getMedian()
delete the memory and then return the value.
C++ supplies std::vector
so you do not have to deal with memory management, why not use those instead?
you should just be able to
delete[] tempArray;
If that doesn't work then I really don't understand the question.
Edit: Place the delete[] line right before return
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.