In order for an application to have no memory leaks, does the number of new in a C++ project match the number of delete?
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 new
ed in multiple places, but all these objects delete
d by the same line of code. In fact this is a common idiom.
Smart pointers, of varying types, generally take many different objects new
ed 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With