What is a memory leak
Memory leak refers to the program's dynamic application of memory is not released after use, resulting in this memory can not be recycled by the operating system.
For example, this program, which requested 4 bytes of space but was not released, has a memory leak of 4 bytes.
#include <iostream>usingnamespacestd;int main(){ intnewint(1); cout <<*p<<endl; return0}
Over time, more and more leaked memory, less usable memory, lighter performance, and heavy system crashes.
In general, when a memory leak occurs, a reboot can reclaim the leaked memory. However, for Linux, usually run server programs, can not be restarted at will, the memory leak on the issue of extra care.
Memory leak features
Difficult to reproduce-to run until long enough to be exposed.
Difficult to locate-the error location is random and does not see any connection to the memory leak code.
The simplest way
In order to avoid writing a memory leak program, there are usually such programming specifications that require us to apply and release paired occurrences when writing a program. Because every application means that there must be a release that corresponds to it.
Based on this feature, a simple method is to count the number of requests and releases in the code, and if the number of applications and releases is different, it is considered a memory leak.
#include "stdio.h"#include "stdlib.h"intMalloc_count, Free_count;void* MY_MALLOC (intSize) {malloc_count++;return malloc(size);}voidMy_free (void*p) {free_count++; Free(p);}intMain () {count =0;int*P1 = (int*) My_malloc (Sizeif (int))int*P2 = (int*) My_malloc (Sizeif (int))printf("%d,%d", p1, p2); My_free (p1);if(Malloc_count! = free_count)printf("Memory leak!\n");return 0}
Method analysis
Intuitive, easy to understand, easy to implement
1. This method requires that the results be known at the end of the run when the print analysis is generated.
2. This method requires that all functions that request and free space be encapsulated and modified to call the encapsulated function where it is called. Although the application/release memory interface in C is not many, but for a large project, the place to call these interfaces is a lot of, to replace all is a relatively large amount of work.
3. Only applicable to C language, not for C + +
4. Not applicable for the library being called. If you want to apply to the library, modify the library code
5. Can only detect leakage, but no specific information, such as how much space leaked
6. Does not indicate which line of code caused the leak
Improved
Although this method is simple, there are many shortcomings that can not be really applied to the project. Want to know how to improve, and see tell.
Detection of memory leaks in Linux (i) the simplest method