4

In my code, I am allocating an integer array using new. After that I am wrapping this pointer to an auto_ptr. I know that the auto_ptr call its destructor automatically. Since my auto_ptr is pointing to an array (allocated using new), Will the array get deleted along with auto_ptr or will it cause a memory leak. Here is my sample code.

std::auto_ptr<int> pointer;

void function()
{
  int *array = new int[2];
  array[0] = 10;
  array[1] = 20;

  pointer.reset((int*) array);
}

int _tmain(int argc, _TCHAR* argv[])
{

    function();
return 0;
}
Aneesh Narayanan
  • 3,220
  • 11
  • 31
  • 48

3 Answers3

9

The array will not be deleted correctly. auto_ptr uses delete contained_item;. For an array it would need to use delete [] contained_item; instead. The result is undefined behavior.

As James McNellis said, you really want std::vector here -- no new, no auto_ptr and no worries.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
8

You can not use std::auto_ptr to handle dynamic arrays, because it can not know how to differentiate between delete and delete[].

Moreover, auto_ptr is deprecated, in C++11 you can use std::unique_ptr with:

int *array = new int[2];
std::unique_ptr<int[]> pointer(array);
fatihk
  • 7,789
  • 1
  • 26
  • 48
  • You would need to instantiate it with a special deleter, otherwise it will just call `delete`. – juanchopanza Jul 17 '13 at 05:44
  • 3
    @juanchopanza, in http://msdn.microsoft.com/en-us/library/vstudio/ee410601.aspx it is stated that a partial specialization unique_ptrmanages array objects allocated with new[], and has the default deleter default_delete, specialized to call delete[] _Ptr – fatihk Jul 17 '13 at 05:49
  • 1
    @juanchopanza The template specialization will take care of it. No need of custom deleter. – Jagannath Jul 17 '13 at 05:49
  • Perfect, that is something I didn't know! – juanchopanza Jul 17 '13 at 05:50
  • 1
    I prefer `std::unique_ptr pointer(new int[2]);` as it avoids copying the pointer. Note, that with C++14 there will be `make_unique()` as we have `make_shared()` already today. This will provide strong exception safety when allocation unique pointers – ogni42 Jul 17 '13 at 06:19
1

As others said auto_ptr is the wrong thing to use, std::vector is best. But you may also use boost::scoped_array. But note that you want to reset at time of creation otherwise you might as well use delete. pointer.reset(new int[2]);

or better yet like this boost::scoped_array arr(new int[2]);

Also there is no point to to create a static std::auto_ptr pointer; in global scope. This means it will get deleted only when the program exists, that happens anyway even if you leak memory.

madnut
  • 124
  • 5