Search code examples
c++memory-leaksauto-ptr

std::auto_ptr, delete[] and leaks


Why this code does not cause memory leaks?

int iterCount = 1000;
int sizeBig = 100000;
for (int i = 0; i < iterCount; i++)
{
   std::auto_ptr<char> buffer(new char[sizeBig]);
}

WinXP sp2, Compiler : BCB.05.03


Solution

  • Because you're (un)lucky. auto_ptr calls delete, not delete []. This is undefined behavior.

    Try doing something like this and see if you get as lucky:

    struct Foo
    {
        char *bar;
        Foo(void) : bar(new char[100]) { }
        ~Foo(void) { delete [] bar; }
    }
    
    int iterCount = 1000;
    int sizeBig = 100000;
    for (int i = 0; i < iterCount; i++)
    {
       std::auto_ptr<Foo> buffer(new Foo[sizeBig]);
    }
    

    The idea here is that your destructor for Foo will not be called.


    The reason is something like this: When you say delete[] p, the implementation of delete[] is suppose to go to each element in the array, call its destructor, then free the memory pointed to by p. Similarly, delete p is suppose to call the destructor on p, then free the memory.

    char's don't have a destructor, so it's just going to delete the memory pointed to by p. In my code above, it is not going to destruct each element in the array (because it's not calling delete[]), so some Foo's will leave their local bar variable un-deleted.