Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory leaks in C++ (via new+delete)

In order for an application to have no memory leaks, does the number of new in a C++ project match the number of delete?

like image 739
joemoe Avatar asked Aug 30 '09 21:08

joemoe


2 Answers

If you mean do you need the same number of instances of delete in your source code as you have instances of new, then no. You can have objects newed in multiple places, but all these objects deleted by the same line of code. In fact this is a common idiom.

Smart pointers, of varying types, generally take many different objects newed in many places in user code and delete them from a single place in library code.

Edit

Technically, every successfully memory allocation call needs to be matched with a dellocation call that takes the returned pointer from the original allocation call.

Most new expressions result in a call to an operator new that allocates the memory and the constructs an object in the newly allocated memory. Using a delete expression destroys the object and causes a call to an operator delete that should free the allocated memory.

There are new expressions that construct objects in pre-allocated memory (placement new). These should not be matched by a delete expression, but the pre-allocated memory may need to be deallocated in a way that corresponds to the original allocation.

like image 188
CB Bailey Avatar answered Oct 06 '22 19:10

CB Bailey


If you meant "in the source code", then No.

See this code :

int main()
{
    char* buffer = 0; 


    for( int i = 0; i < 42; ++i )
    {
        buffer = new char[1024];
    }

    delete [] buffer; 

    return 0;
}

1 new, 1 delete, ((42 - 1) * 1024) bytes of memory leaked.

If you meant "new and delete call at runtime" then yes. Each memory aquired with new have to be released with delete:

int main()
{
    std::vector<char*> bufferList; // or nullptr or NULL whatever


    for( int i = 0; i < 42; ++i )
    {
        bufferList.push_back( new char[1024] );
    }

    for( int i = 0; i < bufferList.size(); ++i )
    {
        delete [] bufferList[i]; 
    }

    return 0;
}

Now at execution we got a delete executed for each new executed <=> no leak.

like image 45
Klaim Avatar answered Oct 06 '22 19:10

Klaim