memory leak program execution general concepts code translation compiler compiletime optimizing compiler intermediate representation ir execution runtime system runtime executable interpreter virtual machine types of code source code object code bytecode machine code microcode compilation strategies justintime jit tracing justintime aheadoftime aot transcompilation recompilation notable runtimes android runtime art common language runtime clr mono crt0 hhvm java virtual machine jvm objectivec v8 nodejs pypy zend engine notable compilers toolchains gnu compiler collection gcc llvm clang vte in computer science a memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations a memory leak has symptoms similar to a number of other problems and generally can only be diagnosed by a programmer with access to the programs source code a space leak occurs when a computer program uses more memory than necessary in contrast to memory leaks where the leaked memory is never released the memory consumed by a space leak is released but later than expected because they can exhaust available system memory as an application runs memory leaks are often the cause of or a contributing factor to software aging consequences a memory leak reduces the performance of the computer by reducing the amount of available memory eventually in the worst case too much of the available memory may become allocated and all or part of the system or device stops working correctly the application fails or the system slows down vastly due to thrashing memory leaks may not be serious or even detectable by normal means in modern operating systems normal memory used by an application is released when the application terminates this means that a memory leak in a program that only runs for a short time may not be noticed and is rarely serious much more serious leaks include those where the program runs for an extended time and consumes additional memory over time such as background tasks on servers but especially in embedded devices which may be left running for many years where new memory is allocated frequently for onetime tasks such as when rendering the frames of a computer game or animated video where the program can request memory such as shared memory that is not released even when the program terminates where memory is very limited such as in an embedded system or portable device where the leak occurs within the operating system or memory manager when a system device driver causes the leak running on an operating system that does not automatically release memory on program termination an example of memory leak the following example written in pseudocode is intended to show how a memory leak can come about and its effects without needing any programming knowledge the program in this case is part of some very simple software designed to control an elevator this part of the program is run whenever anyone inside the elevator presses the button for a floor when a button is pressed get some memory which will be used to remember the floor number put the floor number into the memory are we already on the target floor if so we have nothing to do finished otherwise wait until the lift is idle go to the required floor release the memory we used to remember the floor number the memory leak would occur if the floor number requested is the same floor that the elevator is on the condition for releasing the memory would be skipped each time this case occurs more memory is leaked cases like this wouldnt usually have any immediate effects people do not often press the button for the floor they are already on and in any case the elevator might have enough spare memory that this could happen hundreds or thousands of times however the elevator will eventually run out of memory this could take months or years so it might not be discovered despite thorough testing the consequences would be unpleasant at the very least the elevator would stop responding to requests to move to another floor such as when an attempt is made to call the elevator or when someone is inside and presses the floor buttons if other parts of the program need memory a part assigned to open and close the door for example then someone may be trapped inside or if no one is in then no one would be able to use the elevator since the software cannot open the door the memory leak lasts until the system is reset for example if the elevators power were turned off or in a power outage the program would stop running when power was turned on again the program would restart and all the memory would be available again but the slow process of memory leak would restart together with the program eventually prejudicing the correct running of the system the leak in the above example can be corrected by bringing the release operation outside of the conditional when a button is pressed get some memory which will be used to remember the floor number put the floor number into the memory are we already on the target floor if not wait until the lift is idle go to the required floor release the memory we used to remember the floor number programming issues memory leaks are a common error in programming especially when using languages that have no built in automatic garbage collection such as c and c typically a memory leak occurs because dynamically allocated memory has become unreachable the prevalence of memory leak bugs has led to the development of a number of debugging tools to detect unreachable memory boundschecker deleaker ibm rational purify valgrind parasoft insure dr memory and memwatch are some of the more popular memory debuggers for c and c programs conservative garbage collection capabilities can be added to any programming language that lacks it as a builtin feature and libraries for doing this are available for c and c programs a conservative collector finds and reclaims most but not all unreachable memory although the memory manager can recover unreachable memory it cannot free memory that is still reachable and therefore potentially still useful modern memory managers therefore provide techniques for programmers to semantically mark memory with varying levels of usefulness which correspond to varying levels of reachability the memory manager does not free an object that is strongly reachable an object is strongly reachable if it is reachable either directly by a strong reference or indirectly by a chain of strong references a strong reference is a reference that unlike a weak reference prevents an object from being garbage collected to prevent this the developer is responsible for cleaning up references after use typically by setting the reference to null once it is no longer needed and if necessary by deregistering any event listeners that maintain strong references to the object in general automatic memory management is more robust and convenient for developers as they dont need to implement freeing routines or worry about the sequence in which cleanup is performed or be concerned about whether or not an object is still referenced it is easier for a programmer to know when a reference is no longer needed than to know when an object is no longer referenced however automatic memory management can impose a performance overhead and it does not eliminate all of the programming errors that cause memory leaks raii resource acquisition is initialization raii short for resource acquisition is initialization is an approach to the problem commonly taken in c d and ada it involves associating scoped objects with the acquired resources and automatically releasing the resources once the objects are out of scope unlike garbage collection raii has the advantage of knowing when objects exist and when they do not compare the following c and c examples c version include stdlibh void fint n int array callocn sizeofint dosomeworkarray freearray c version include vector void fint n stdvectorint array n dosomeworkarray the c version as implemented in the example requires explicit deallocation the array is dynamically allocated from the heap in most c implementations and continues to exist until explicitly freed the c version requires no explicit deallocation it will always occur automatically as soon as the object array goes out of scope including if an exception is thrown this avoids some of the overhead of garbage collection schemes and because object destructors can free resources other than memory raii helps to prevent the leaking of input and output resources accessed through a handle which markandsweep garbage collection does not handle gracefully these include open files open windows user notifications objects in a graphics drawing library thread synchronisation primitives such as critical sections network connections and connections to the windows registry or another database however using raii correctly is not always easy and has its own pitfalls for instance if one is not careful it is possible to create dangling pointers or references by returning data by reference only to have that data be deleted when its containing object goes out of scope d uses a combination of raii and garbage collection employing automatic destruction when it is clear that an object cannot be accessed outside its original scope and garbage collection otherwise reference counting and cyclic references more modern garbage collection schemes are often based on a notion of reachability if you dont have a usable reference to the memory in question it can be collected other garbage collection schemes can be based on reference counting where an object is responsible for keeping track of how many references are pointing to it if the number goes down to zero the object is expected to release itself and allow its memory to be reclaimed the flaw with this model is that it doesnt cope with cyclic references and this is why nowadays most programmers are prepared to accept the burden of the more costly mark and sweep type of systems the following visual basic code illustrates the canonical referencecounting memory leak dim a b set a createobjectsomething set b createobjectsomething at this point the two objects each have one reference set amember b set bmember a now they each have two references set a nothing you could still get out of it set b nothing and now youve got a memory leak end in practice this trivial example would be spotted straight away and fixed in most real examples the cycle of references spans more than two objects and is more difficult to detect a wellknown example of this kind of leak came to prominence with the rise of ajax programming techniques in web browsers in the lapsed listener problem javascript code which associated a dom element with an event handler and failed to remove the reference before exiting would leak memory ajax web pages keep a given dom alive for a lot longer than traditional web pages so this leak was much more apparent effects if a program has a memory leak and its memory usage is steadily increasing there will not usually be an immediate symptom every physical system has a finite amount of memory and if the memory leak is not contained for example by restarting the leaking program it will eventually cause problems most modern consumer desktop operating systems have both main memory which is physically housed in ram microchips and secondary storage such as a hard drive memory allocation is dynamic each process gets as much memory as it requests active pages are transferred into main memory for fast access inactive pages are pushed out to secondary storage to make room as needed when a single process starts consuming a large amount of memory it usually occupies more and more of main memory pushing other programs out to secondary storage usually significantly slowing performance of the system even if the leaking program is terminated it may take some time for other programs to swap back into main memory and for performance to return to normal when all the memory on a system is exhausted whether there is virtual memory or only main memory such as on an embedded system any attempt to allocate more memory will fail this usually causes the program attempting to allocate the memory to terminate itself or to generate a segmentation fault some programs are designed to recover from this situation possibly by falling back on prereserved memory the first program to experience the outofmemory may or may not be the program that has the memory leak some multitasking operating systems have special mechanisms to deal with an outofmemory condition such as killing processes at random which may affect innocent processes or killing the largest process in memory which presumably is the one causing the problem some operating systems have a perprocess memory limit to prevent any one program from hogging all of the memory on the system the disadvantage to this arrangement is that the operating system sometimes must be reconfigured to allow proper operation of programs that legitimately require large amounts of memory such as those dealing with graphics video or scientific calculations the sawtooth pattern of memory utilization the sudden drop in used memory is a candidate symptom for a memory leak if the memory leak is in the kernel the operating system itself will likely fail computers without sophisticated memory management such as embedded systems may also completely fail from a persistent memory leak publicly accessible systems such as web servers or routers are prone to denialofservice attacks if an attacker discovers a sequence of operations which can trigger a leak such a sequence is known as an exploit a sawtooth pattern of memory utilization may be an indicator of a memory leak within an application particularly if the vertical drops coincide with reboots or restarts of that application care should be taken though because garbage collection points could also cause such a pattern and would show a healthy usage of the heap other memory consumers note that constantly increasing memory usage is not necessarily evidence of a memory leak some applications will store ever increasing amounts of information in memory eg as a cache if the cache can grow so large as to cause problems this may be a programming or design error but is not a memory leak as the information remains nominally in use in other cases programs may require an unreasonably large amount of memory because the programmer has assumed memory is always sufficient for a particular task for example a graphics file processor might start by reading the entire contents of an image file and storing it all into memory something that is not viable where a very large image exceeds available memory to put it another way a memory leak arises from a particular kind of programming error and without access to the program code someone seeing symptoms can only guess that there might be a memory leak it would be better to use terms such as constantly increasing memory use where no such inside knowledge exists a simple example in c the following c function deliberately leaks memory by losing the pointer to the allocated memory the leak can be said to occur as soon as the pointer a goes out of scope ie when functionwhichallocates returns without freeing a include stdlibh void functionwhichallocatesvoid allocate an array of 45 floats float a mallocsizeoffloat 45 additional code making use of a return to main having forgotten to free the memory we mallocd int mainvoid functionwhichallocates the pointer a no longer exists and therefore cannot be freed but the memory is still allocated a leak has occurred buffer overflow memory management memory debugger plumbr is a popular memory leak detection tool for applications running on java virtual machine nmon short for nigels monitor is a popular system monitor tool for the aix and linux operating systems visual leak detector for visual studio open source valgrind open source deleaker for visual studio proprietary detecting a memory leak using mfc debugging support article memory leak detection in embedded systems by cal erickson vtememory management memory management as a function of an operating system manual memory management static memory allocation c dynamic memory allocation new and delete c virtual memory demand paging page table paging virtual memory compression hardware memory management unit translation lookaside buffer garbage collection boehm garbage collector concurrent mark sweep collector finalizer garbage garbagefirst collector markcompact algorithm reference counting tracing garbage collection strong reference weak reference memory segmentation protected mode real mode virtual 8086 mode x86 memory segmentation memory safety buffer overflow buffer overread dangling pointer stack overflow issues fragmentation memory leak unreachable memory other automatic variable international symposium on memory management regionbased memory management 