Memory leak:
When we allocate a piece of memory and forgot to de-allocate it, or it is not de-allocated properly. If the program does not use that memory further, it is still reserved and another program cannot use allocated memory until it is de-allocated, this situation is called a memory leak.
How the memory leaks occur in C++?
Memory Leaks:
As we said earlier memory leaks occur when data are allocated at runtime but not de-allocated once they are no longer needed. When an allocation has no matching de-allocation, that’s a leak, and the heap debugger can help us find them.
By the buffer overruns, we may get memory leaks:
When we are trying to write the data more than that we have allocated in the heap. It leads to corrupting the data. We may get the unpredicted output from our program because the memory location has the wrong value.
When we forgot to initialize Memory, i.e. un-initialized memory:
Memory leaks have occurred when we try to access the data that is not initialized. C++ allows us to allocate the variables without initial values.
How to find memory leaks in C++?
Below are some instructions that we need to remember while writing the code.
First, we need to understand the operator basics. In C++ language we have new and delete operators.
Operator “new” allocates heap memory. The “delete” operator frees heap memory. For every “new,” you should use a “delete” so that you free the same memory you allocated:
1 2 |
char* pcchStr = new char [30]; // Allocates delete [] pcchStr; // de-allocates |
See below steps . Every dynamic variable (allocated memory on the heap) needs to be associated with a pointer. When a dynamic variable becomes disassociated from its pointer(s), it becomes impossible to clear.
1 2 3 4 5 6 7 8 9 10 11 |
char* pcchStr1 = new char [40]; char* pcchStr2 = new char [90]; strcpy(pcchStr1, "Test memory leak"); pcchStr2 = pcchStr1; // Bad! These bytes we cannot free delete [] pcchStr2; // good approach delete [] pcchStr1; // get access violation. |
we need to focus on the local pointers which are also dangerous.
A pointer you declare in a function is allocated on the stack, but the dynamic variable it points to is allocated on the heap. If you do not delete it, it will keep it up after the program exits from the function:
1 2 3 4 5 6 7 |
void MyFun (int iVal){ char* ptr = new char [iVal]; // forgot to delete that. } |
We need to pay attention to the square braces after “delete.” Use “delete” by itself to free a single object. Use “delete” [] with square brackets to free a heap array. Don’t do something like this:
1 2 3 4 5 6 7 |
char* StrLine = new char; delete [] StrLine; char* StrLineArr= new char [15]; delete StrLineArr; |