The most common memory / resource leak errors

All good C ++ programmers know how to avoid memory leaks (or resources such as sockets):

  • Always use smart pointers, i.e. e .: std::auto_ptr, boost::shared_ptr.
  • Always remember the ownership of the object: who owns, who refers, who is responsible, etc.

But memory leaks are still occurring. Indicate the most common problems when you find a memory leak in a program, even if you used the above methods.

I start:

Sometimes you forget to define the base class destructor as virtual. Thus, all derived classes refer to a pointer to a base class that was not correctly destroyed and therefore leaked.

+5
source share
5 answers

There are many other types of errors than just leaks. In order from worst to best:

Memory corruption.

Data is stored in an area where it should not be. This leads to both the majority of security problems and the best, most difficult to track.

  • "Random Location"
    • Data is stored in a memory location that the user can control.
    • Data is stored in an array without checking indexes.
    • An object of the type obtained from Xis stored in the array element reserved for the base type X, and the size is Xlarger than the size of its base.
  • Lifetime corruption
    • Data is stored in the memory after it is freed.
    • (, new/free, malloc/delete)
    • delete free .

, , .

  • : new[]/delete new[]/delete[].
  • - , , , smart_ptr , weak_ptr .
  • - - , , .
  • - , , , . , , , .
+5

, std::auto_ptr boost::shared_ptr (2) , .

+2
  • , "" . , ... ( )
  • stl:: multimap ( , ) , .
+2

, , ( smartpointers):

class A { 
public:
    int avery_useful_calculation()const { return 4; } 
private:
    // class shouldn't be instantiated as an automatic variable (on stack)
    virtual ~A(){} 
};

// client code: needs a very useful calculation

int i = (new A)->avery_useful_calculation();
0

, , , "" .

"" , try {} __finally {}, ( -, , -)

0

All Articles