c++ - Different ways of leaking memory -


the basic concept of memory leaking mismatch of new/delete operation during code execution, either due wrong coding practices or either in cases of errors when delete operation skipped.

but asked question in interview other ways in memory can leak. had no answer it. it?

common dynamic memory problems are:

  • dynamic memory allocation new , not deallocating delete.
  • dynamic memory allocation new[] , deallocating delete.
  • dynamic memory allocation new , deallocate free.
  • dynamic memory allocation malloc , deallocate delete.

in addition memory leaks/memory corruption last 3 scenarios cause dreaded undefined behavior.

a few other potential memory leak causing scenarios can recollect are:

  • if pointer, pointing dynamically allocated memory region re-assigned new value before being deallocated, lead dangling pointer , memory leak.

a code example:

char *a = new[128];     char *b = new[128];     b = a;     delete[]a;     delete[]b; // not deallocate pointer original allocated memory. 

- pointers in stl containers

a more common , encountered scenario is, storing pointers pointing dynamically allocated types in stl containers. important note stl containers take ownership of deleting contained object only if not pointer type.
1 has explicitly iterate through container , delete each contained type before deleting container itself. not doing causes memory leak.
here example of such scenario.

- non virtual base class destructor problem

deleting pointer base class points dynamically allocated object of derived class on heap. results in undefined behavior.

an code example:

class myclass {     public:     virtual void dosomething(){} };  class myclass2 : public myclass  {      private:           std::string str;       public: myclass2( std::string& s)      {           str=s;      }       virtual void dosomething(){} };    int main() {        std::str hello("hello");       myclass * p = new myclass2(hello);        if( p )       {          delete p;        }       return 0; } 

in example destructor myclass::~myclass() gets called , myclass2::~myclass2() never gets called. appropriate deallocation 1 need,

myclass::virtual ~myclass(){} 

- calling delete on void pointer

a code example:

void dosomething( void * p )  {     //do interesting     if(p)        delete p;  }  int main() {     a* p = new a();     dosomething(p);     return 0; } 

calling delete on void pointer in above example, cause memory leak , undefined behavior.


Comments

Popular posts from this blog

c++ - Is it possible to compile a VST on linux? -

java - Output of Eclipse is rubbish -

jquery - Confused with JSON data and normal data in Django ajax request -