Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does returning a dynamically-allocated array from a function cause a memory leak?

Tags:

c++

I'm asking this question to relieve myself of the confusion I've been having about the following program. I know using an array in certain contexts will make the array to decay to a single pointer to its first element. I have a function that returns this array by pointer (this function is created using new[]). Will the array decay, causing the pointer to point only to the first element? Here is an example:

int *foo() {
    int *t = new int[10];

    return t;
}

int main() {
    int *p = foo();
}

This is where the confusion follows. I don't know if p points to the first element or to the entire array. So I have the following questions:

  • Does returning the array by pointer cause the decay of it (and consequentially cause a memory leak)?
  • Does p point to the array's first element?
  • Does using delete[] on p cause undefined behavior if the above two are true?

I'm hoping these questions can be answered so I can fully understand this program. Thank you.

like image 815
Me myself and I Avatar asked Feb 17 '13 23:02

Me myself and I


1 Answers

Does returning the array by pointer cause the decay of it (and consequentially case a memory leak)?

You are actually returning a copy of t, which is a pointer. It already points at the first element of a dynamically allocated array. There would only be a memory leak if you failed to call delete [] on it.

Does p point to the array's first element?

Yes

Does using delete[] on p cause undefined behavior if the above two are true?

No, it is fine to do that. As long as the function is returning a pointer to a dynamically allocated array.

You have identified a serious problem with this idiom: you cannot know if you are getting a pointer to an element, a pointer to the first element of a dynamically allocated array, a pointer to a global. You cannot know by looking at the return type of the function whether you need to call delete, delete [], or not call delete at all. Solution: do not return a pointer! Return a type that beter expresses what is going on, and that takes care of managing its own resources (std::vector, std::array, std::unique_ptr, std::shared_ptr...).

like image 139
juanchopanza Avatar answered Nov 15 '22 03:11

juanchopanza