Memory Leak

Programmers generally deal with five areas of memory: 
Global namespace -- for global variable 
The heap -- for pointer 
Registers -- for important registers like stack pointer, top of stack
Code space -- program code 
The stack -- local variable


The stack is cleaned automatically when a function returns. Once local variables go out of scope, they are removed from the stack. The heap is not cleaned until your program ends, and it is our responsibility to free the memory we reserved when we done with it. Leaving items hanging around in the heap when you no longer need them is known as a memory leak. The advantage to the heap is that the memory we reserve remains available until we explicitly free it. If we reserve memory on the heap while in a function, the memory is still available when the function returns. The advantage of accessing memory in this way, rather than using global variables, is that only functions with access to the pointer have access to the data. This provides a tightly controlled interface to that data, and it eliminates the problem of one function changing that data in unexpected and unanticipated way. 

When we finished with our area of memory, we must call delete on the pointer, which returns the memory to the heap. When the function in which it is declared returns, that pointer goes out of scope and is lost but the memory allocated by pointer is not freed automatically, Hence that memory becomes unavailable. This situation is called as a memory leak, because that memory can’t be recovered until the program ends. It is as though the memory has leaked out of your computer. Another way you might inadvertently create a memory leak is by reassigning your pointer before deleting the memory to which it points.
Consider this code fragment:
unsigned short int *pPointer = new unsigned short int;
*pPointer = 72; 

pPointer = new unsigned short int;

*pPointer = 84;
The code should have been written like this:

unsigned short int *pPointer = new unsigned short int;
*pPointer = 72; 

delete pPointer; 

pPointer = new unsigned short int; 

*pPointer = 84;
For every time in your program that you call new, there should be a call to delete. It is important to keep track of which pointer owns an area of memory and to ensure that the memory is returned to the heap when you are done with it. 

No comments:

Post a Comment

Rendering 3D maps on the web using opesource javascript library Cesium

This is a simple 3D viewer using the Cesium javascript library. The example code can be found here . Click on question-mark symbol on upp...