c++ - How to guard against memory leaks? -


I was recently interviewed for a C ++ position, and I was asked to make a memory leak How to stop me I know that I did not give a satisfactory answer to that question, so I'm throwing it to you, what are the best ways to prevent memory leaks?

Thank you!

What are the answers to all the answers given below so far: Delete Avoid calling.

The programmer has to call delete at any time, you have a potential memory leak instead; Delete instead of having the call automatically Let C ++ guarantee that local goods have their destructors when they go out of the scope. Use that guarantee to ensure that your memory allocation has been automatically removed. In its most general form, this technique means that each memory allocation should be wrapped within a simple class, whose manufacturer allocates the necessary memory, and the destroyer releases it.

Since it is such a commonly used and widely applied technique, smart pointer classes have been created which reduce the amount of boilerplate code. Rather than assigning memory, their constructors take an indicator for already allocated memory allocation, and store it. When Smart Pointer exits the scope, it is able to remove the allocation.

Of course, depending on usage, different semantics can be said. Do you just need a simple case, where the allocation will actually run until the cover class will survive? Then use boost :: scoped_ptr or, if you can not promote, then std :: auto_ptr . Do you have an unknown number of objects that reference allocation, which have no knowledge about how long will they stay? Then the reference-count boost :: share_ptr is a good solution.

But you do not have to use smart pointers. Standard library containers also do the tricks they internally allocate the memory required to store copies of those items that you put in them, and When they are removed, they release the memory again. That's why the user does not have to call either new or delete .

There are countless variations of this technique, whose obligation is to change the initial memory allocation, or when deallocation should be done.

But those who are equal in common, the answer to your question is: RAII idioms: resource acquisition is in progress. Memory allocation is a type of resource when an object is initialized, and the object is destroyed by it, should get the resource.

Build C ++ scope and the rules of life do your work for you. Never call delete outside the RAI object, whether it is a container class, a smart pointer or an allocation to some ad-hoc wrapper objects to handle the resources it has handed.

If all delete calls happen automatically, you can not forget them. And then there is no way you can leak memory.


Comments

Popular posts from this blog

sql - dynamically varied number of conditions in the 'where' statement using LINQ -

asp.net mvc - Dynamically Generated Ajax.BeginForm -

Debug on symbian -