Wednesday, 26 November 2014

What is a Memory leak? How the memory leaks occur in C++?

What is a Memory leak? How the memory leaks occur in C++? 

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 other program cannot use allocated memory until it is de-allocated, this situation is called memory leak.

How the memory leaks occur in C++?
Memory Leaks:

As we said earlier memory leaks occur when data that 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 corrupt 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 are 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++?

The below are some instructions that we need to remember while writing the code.

We need to get the proficiency in C++, try to learn more about the C++

Understand the C++ compiler.

Try to improve the debugging skills.

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:
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.
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:
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:
char* StrLine = new char;

delete [] StrLine;

char* StrLineArr= new char [15];

delete StrLineArr; 

No comments: