Reputation: 5585
I have the following code which works fine except I'm not sure if I need to delete the returned_array
pointer in the int main()
or if its automatically deleted. I will guess its not automatically deleted and assume I should use delete returned_array;
after the cout
is finished. Any suggestions?
#include <iostream>
double* pass_return_array(double passed[])
{
double* returned_array = new double[3];
for(int index = 0; index < 3; index++)
returned_array[index] = passed[index];
return returned_array;
}
int main()
{
double passed[3];
double* returned_array;
for(int index = 0; index < 3; index++)
passed[index] = index + 100;
returned_array = pass_return_array(passed);
for(int index = 0; index < 3; index++)
std::cout<<returned_array[index]<<std::endl;
return 0;
}
Upvotes: 0
Views: 1222
Reputation: 881103
It's good practice to clean up all resources that you allocate regardless of whether or not you think it will be done automagically for you.
It's also good practice for the responsibility for a resource to follow the resource itself. That means, if you return some dynamically allocated memory from a function, you also "return" the responsibility for it.
That's not to say it has to be cleaned up in the function caller since that may break encapsulation (you don't necessarily even know if it's dynamically allocated). But, even if you pass the resource back to the code/library that created it, that is again passing the responsibility too, as per the following pseudo-code:
def makeSomething():
something = unknownMethodForCreatingSomething()
#makeSomething() has responsibility here but passes it off to caller
return something
def killSomething(something):
# Responsibility with killSomething() at this point
equallyUnknownMethodForDestroyingSomething(something)
def main():
xyzzy = makeSomething()
# main() has responsibility for xyzzy here but hands it off in next line
killSomething (xyzzy)
Upvotes: 2
Reputation: 25927
You are right: you created the array in the function, you also are responsible for its deallocation. You should call delete[] returned_array;
as soon as you no longer need it.
Note, that OS always cleans up all resources allocated by the program when it terminates, so there won't be any system-wide memory leaks. But it's a very bad practice to leave the deallocation to the OS, you should always deallocate all resources you allocated (and that includes other kinds of things - for example handles to files or brushes).
Consider using std::vector
or std::array
instead - if used as a simple local variable, they will take care of memory they allocated and you won't have to remember about it. That's the power of C++ in work :)
Upvotes: 4