0

I have a function that allocates memory using the new keyword.

That array gets returned from the function, but I need to somehow free it. Is it ever freed after the function returns, or is it up to the receiving code to free the array after it is done with it?

Should I just make this array a member variable, and free it in the class destructor?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Derek
  • 11,715
  • 32
  • 127
  • 228

4 Answers4

4

If you allocate memory explicitly with new, you must free it explicitly with delete. Local variables will be freed upon return; classes like vector may do some allocation behind the scenes but they will clean that up for you.

In general, C++ largely lets you pick your memory management model. You can stick with locals and non-pointer class members and get scope-based allocation. You can play with pointers and malloc/free or new/delete (but never free() a new'd pointer and vice versa!). Or, you could grab Boost and get boost::shared_ptr for reference counting semantics.

Walter Mundt
  • 24,753
  • 5
  • 53
  • 61
3

Should I just make this array a member variable, and free it in the class deconstructor?

That's generally a very good idea, but why reinvent the wheel? Just use std::vector<T>.

fredoverflow
  • 256,549
  • 94
  • 388
  • 662
  • typically trying to stay away from using any of those standard libs. Seems easier to deal with normal arrays for some GPU processing I am doing wtih this project – Derek Jan 25 '11 at 21:40
  • @Derek: You should ask how you can use both. And if you really decide not to, yes, you need to make a wrapper class (don't forget to either disable the copy constructor and copy assignment operator, or [implement them](http://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom)). – GManNickG Jan 25 '11 at 22:55
2

It depends. You need to define who has got the ownership of such object.

You can allocate the array in your function, return it, and let the caller free it, or put a pointer to it in a class which will destroy the pointer in the destructor.

If the ownership for such object should be shared among many entities you should use something like a shared_ptr.

I'd also suggest to always use some kind of smart pointer to handle your raw pointers.

peoro
  • 25,562
  • 20
  • 98
  • 150
0

Take a look at boost::shared_array. It does what you need. Either that, or use std::vector

BЈовић
  • 62,405
  • 41
  • 173
  • 273