Memory leakage occurs in C++ when programmers allocates memory by using new keyword and forgets to deallocate the memory by using delete() function or delete operator. One of the most memory leakage occurs in C++ by using wrong delete operator.
The delete operator should be used to free a single allocated memory space, whereas the delete  operator should be used to free an array of data values.
Disadvantage with memory leakage:
If a program has memory leaks, then its memory usage is satirically increasing since all systems have limited amount of memory and memory is costly. Hence it will create problems.
Example of memory leakage in C++
How to avoid Memory Leak?
- Instead of managing memory manually, try to use smart pointers where applicable.
- use std::string instead of char *. The std::string class handles all memory management internally, and it’s fast and well-optimized.
- Never use a raw pointer unless it’s to interface with an older lib.
- The best way to avoid memory leaks in C++ is to have as few new/delete calls at the program level as possible – ideally NONE. Anything that requires dynamic memory should be buried inside an RAII object that releases the memory when it goes out of scope. RAAI allocate memory in constructor and release it in destructor, so that memory is garanteed to be deallocated when the variable leave the current scope.
- Allocate memory by new keyword and deallocate memory by delete keyword and write all code between them.
Example to handle memory leaks
Therefore, Always write delete pointer for matching of new pointer in C++ and always write code between these new and delete as explained in above example. In above example, no memory is wasted because when we are coming out from the function we are deallocating the memory by using delete function.
- What is Memory Leak? How can we avoid?
- Why we should avoid using std::endl
- What are Wild Pointers? How can we avoid?
- Introduction to memory and memory units
- 2D and 2.5D Memory organization
- What is Dynamic Memory Allocation?
- C++ Program that will fill whole memory
- How to deallocate memory without using free() in C?
- Virtual Memory | Questions
- Memory Layout of C Programs
- How does free() know the size of memory to be deallocated?
- C | Dynamic Memory Allocation | Question 1
- Virtual Memory | Operating System
- new and delete operators in C++ for dynamic memory
- C | Dynamic Memory Allocation | Question 2
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.