[ACCEPTED]-Memory leaks in C++ (via new+delete)-memory-leaks
If you mean do you need the same number 23 of instances of delete
in your source code as 22 you have instances of new
, then no. You can 21 have objects new
ed in multiple places, but 20 all these objects delete
d by the same line of 19 code. In fact this is a common idiom.
Smart 18 pointers, of varying types, generally take 17 many different objects new
ed in many places 16 in user code and delete
them from a single place 15 in library code.
Edit
Technically, every successfully 14 memory allocation call needs to be matched 13 with a dellocation call that takes the returned 12 pointer from the original allocation call.
Most 11 new
expressions result in a call to an operator new
that 10 allocates the memory and the constructs 9 an object in the newly allocated memory. Using 8 a delete
expression destroys the object and causes 7 a call to an operator delete
that should free the allocated 6 memory.
There are new expressions that construct 5 objects in pre-allocated memory (placement 4 new
). These should not be matched by a delete expression, but 3 the pre-allocated memory may need to be 2 deallocated in a way that corresponds to 1 the original allocation.
If you meant "in the source code", then 6 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 5 delete call at runtime" then yes. Each memory 4 aquired with new have to be released with 3 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 2 executed for each new executed <=> no 1 leak.
Yes. Every new must be matched by a delete.
However, the 4 delete is often hidden from you - for example:
{
std::auto_ptr p( new Foo );
}
Here 3 there is a new, but the delete (which occurs 2 automatically at the end of the block) is 1 hidden in the std::auto_ptr implementation.
There are sophisticated tools like Rational's 6 Purify to test for memory leaks n C++ programs. Unfortunately 5 it is in general a highly non-trivial problem 4 to verify the code itself is free of memory 3 leaks before runtime. Therefore, keep it 2 simple, follow best practices and test as 1 much as possible in runtime.
You need to match a call to new with a call 12 to delete. Since C++ is an object oriented 11 programming language, consider using a class 10 to create (in the constructor) and to delete 9 (in the destructor) the variables declared 8 or used in the class. In fact, that would 7 be taking the advantage of the Resource Acquisition Is Initialization or RAII (for 6 short) idiom. If you don't feel like programming 5 this yourself you can always use memory from the 4 STL.
One important note: if you allocate a variable 3 with a new and your code can throw an exception, you 2 can leak memory if that exception is not 1 caught and the variable deleted accordingly.
Are you asking about run time call count 13 (e.g. counted using a instrumenting profiler)? Having 12 exactly the same number of calls to the 11 new
(excluding placement new) and delete
operators 10 is neither a necessary nor sufficient condition 9 of leak-free code:
- Deleting
NULL
is harmless, so many leak-free programs calldelete
more times thannew
. - A program that calls
delete
as many times asnew
but sometimes deletesNULL
has a leak. So do some programs that calldelete
more times thannew
but sometimes deleteNULL
. - A program that calls
new
more often thandelete
has a leak.
To validate that there 8 are no leaks, you must verify that each 7 address returned from new
is passed to delete
, not 6 just verify that the call count matches. And 5 even that's oversimplifying, since addresses 4 are reused for multiple allocations.
Also, programs 3 that don't leak memory that they have allocated 2 may still leak other resources (such as 1 OS file handles).
Not exactly. Any object allocated using 5 the new operator must be deallocated using 4 the delete operator. Its fine to have an 3 number of operators (new or delete) in different 2 branches.
Personally I use boost's shared_ptr 1 when writing c++ code.
If you are up to finding a preliminary way 16 to detect memory leaks, counting new/deletes 15 won't help at all. However, if you use MS 14 VC, you can use CRT to perform very basic 13 but useful leaks detection for you:
_CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDOUT);
_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
This 12 will cause CRT to call _CrtDumpMemoryLeaks 11 right before CRT is unloaded. If there is 10 any, it will dump them to the console:
Detected memory leaks!
Dumping objects ->
{342} normal block at 0x05A28FD8, 4 bytes long.
Data: < > 00 00 00 00
Object dump complete.
There 9 is also a technique to find the exact place 8 of leak using the number of a block ({342}), but 7 sometimes it is just enough to know whether 6 there are any leaks.
It does not replace 5 the need in proper memory leaks detection 4 tools, but may limit the needs of them.
I 3 always use this technique in unit tests. Allows 2 me to detect very dumb memory leaks very 1 early.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.