A method of memory leak and simple detection

Source: Internet
Author: User

1. What is a memory leak (Leak)? Simply put, the application of a memory space, after use has not been released. The general way it behaves is that the longer the program runs, the more memory is consumed, and eventually all the memory is exhausted, and the entire system crashes. A piece of memory requested by the program, and no pointer to it, then this memory is leaked. 2. The dangers of memory leaks

From the user's point of view of using the program, the memory leak itself does not have any harm, as a general user, there is no sense of memory leaks. What is really harmful is the accumulation of memory leaks, which eventually consumes all the memory of the system. There are mainly the following forms of expression:

1) CPU Resource exhaustion: It is estimated that the machine is unresponsive, keyboard, mouse, network, and so on. This is often seen on windows, especially in the poison. 2) Process ID exhausted: Unable to create a new process, serial or telnet can not be created. 3) Hard drive exhaustion: The machine is dying, swapping memory is useless, the log is useless, and death is normal.

When we write the program, usually use malloc,realloc,new and other functions from the heap allocated to a piece of memory, after use, the program must be responsible for the corresponding call to free or delete the memory block, otherwise, the memory can not be reused, we say this memory leaks. If you want to avoid this problem, or to start from the code, good coding habits and specifications, is to avoid the wrong only way.

3. How do I detect a memory leak?

First: Good coding habits, as far as possible in the memory of the program segment, detect a memory leak. When the program is stable, when it comes to detecting memory leaks, it undoubtedly increases the difficulty and complexity of the exclusions. Using the memory allocation function, once used, remember to use its corresponding function to release.

Heap Memory:

Malloc\realloc------Free

New \new[]----------Delete \delete[]

GlobalAlloc------------GlobalFree

Pay special attention to memory leaks of array objects

Mypointex *pointarray =new Mypointex [100];

The deletion form is:

delete []pointarray;


Second: The allocation of memory pointers in the form of a linked list of self-management, after use is completed from the linked list, the end of the program can check the linked list.

Third: Smart pointer in Boost.

IV: Some common tool plug-ins, such as Ccmalloc, Dmalloc, leaky and so on.

4. Code examples
I mainly want to combine the code to talk about the second method, design ideas are actually very simple, using the list in the STL. Someone might ask, why not use vectors?
The differences between list and vector are as follows:

Vectors allocate a contiguous address space for stored objects, so random access to the elements in the vector is highly efficient. Inserting or deleting an element in Vecotor requires that an existing element be copied and moved. If the objects stored in the vector are large, or the constructors are complex, it is expensive to copy the existing elements because the Copy object calls the copy constructor. For simple small objects, vectors are more efficient than list. Vector expands the capacity by twice times each time it expands, which is very efficient for small objects.

The objects in the list are stored in discrete, random access to an element that needs to traverse the list. Inserting elements into the list, especially at the end of the insert, is highly efficient,
You only need to change the pointer of the element.

Vector applies: Small number of objects change, simple objects, random access elements frequently

List applies: the number of objects varies greatly, objects are complex, insertions and deletions are frequent

#include <iostream> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <       list>using namespace Std;const int nmaxsize = 26;struct node{int count; Node *next[nmaxsize];};     Node *root = null;list <node *> nodememory;void treecreate () {root = (node *) malloc (sizeof (node));       for (int i = 0; i < nmaxsize; ++i) {root->next[i] = NULL;    }}void Treeinsert (char *pstr) {int I, j, len = strlen (PSTR);        Node *p = root;     Node *q = NULL;            for (i = 0; i < len; ++i) {int id = pstr[i]-' a ';             if (p->next[id] = = NULL) {q = (node *) malloc (sizeof (node));            if (q! = NULL) nodememory.push_back (q);              Q->count = 0;             for (j = 0; j < nmaxsize; ++j) {q->next[j] = NULL;         } P->next[id] = q;              }p->next[id]->count++;       p = p->next[id];     }}int treequery (char *pstr) {int I, Len = strlen (PSTR);       int id = 0;      Node *p = root;          for (i = 0; i < len; ++i) {id = pstr[i]-' a ';              p = p->next[id];      if (p = = NULL) return 0; } return p->count;}      void Treedelete (Node *p) {if (p = = NULL) return;       for (int i = 0; i < nmaxsize; ++i) {treedelete (p->next[i]);    } nodememory.remove (P);    Free (p); p = NULL;}     int main (int argc, char **argv) {char szbuffer[16];          int res = 0;     Treecreate ();    int n = 3;         while (n) {gets (szbuffer);             if (strlen (szbuffer) = = 0) break;         Treeinsert (Szbuffer);    n--;           }/* scanf ("%s", szbuffer);     res = Treequery (szbuffer);  printf ("%d\n", res); */For (list<node *>::iterator it = Nodememory.begin (); it! = Nodememory. end (); it++) {cout<<*it<<endl;    } cout<<nodememory.size () <<endl;        Treedelete (root);    if (Nodememory.empty ()) cout<< "has delete the tire tree" <<endl;     Cout<<nodememory.size () <<endl;    System ("pause"); return 0;}

  

The code is simple, the list stores a pointer to the memory space, each time malloc will push the allocated memory pointer to the list, and when free, the list will delete the corresponding content, if all released, the list becomes empty, So you can tell if the memory used is all released?

A method of memory leak and simple detection

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.