1.

Explain memory leak in C++. How can you avoid it?

Answer»

Memory leaking happens in C++ when programmers dynamically allocate memory with the new keyword or using malloc()/calloc() and then forget to deallocate it with the delete() or delete[] operators or the free() function. In C++, one of the most common causes of memory leakage is the use of the incorrect delete operator.

The delete [] operator should be used to free an array of DATA values, whereas the delete operator should be used to clear a single allocated memory space.

 To avoid memory leak: 

  • When possible, UTILISE SMART pointers instead of MANUALLY managing memory.
  • Instead of char *, use std::string. All memory management is handled internally, which is quick and well-optimized.
  • Unless you're interacting with an older library, you should never use a raw pointer.
  • In C++, the SIMPLEST strategy to avoid memory leaks is to have a few new/delete calls as possible at the program level — ideally NONE.
  • Write all code between the new and delete keywords to allocate memory and deallocate memory.


Discussion

No Comment Found