C + + memory leak and detection

Source: Internet
Author: User

Memory leaks in C + + generally refer to memory leaks in the heap. Heap memory is our manual malloc/realloc/new request, the program does not automatically recycle, need to call free or delete manual release, otherwise it will cause a memory leak. Memory leaks should also include the disclosure of system data, such as socket connections, and so on, to be released after use.

Reasons for memory leaks:

To summarize, there are several reasons for memory leaks:

1. Coding error: malloc, realloc, new application memory on the heap, need to manually display the release, call free or delete. The application and release must correspond to the occurrence of malloc/realloc corresponding to the free,new delete. The former does not run the construct/destructor, which will. There may be no difference for C + + built-in data types, but for classes that you construct, you might release system resources or free memory in destructors, so use them.

2. "No master" Memory: After the memory is applied, the pointer points to the starting address of the memory, if the pointer is lost or modified, then the requested memory will be lost and not released.

3. The exception branch causes the resource not to be released: The program performs normally without problems, but if an exception is encountered, the order or branch of normal execution is interrupted and is not executed. So in the exception-handling code, make sure that the system resources are released.

4, implicit memory leak: The program is running in the application of memory, but until the end of the program is released. Some servers request a large amount of memory as a cache, or request a large number of socket resources as connection pools, which continue to occupy until the program exits. The server typically lasts for several months, and not being released in time may result in memory exhaustion.

5, the destructor of the class is a non-virtual function: The destructor is a virtual function, the use of polymorphic to invoke the pointer to the object's destructor, rather than the base class of destructors.


Detection of memory leaks

The key to a memory leak is to record the allocated memory and release the memory to see if it can be matched. Trace the declaration period of each piece of memory, for example: Whenever a piece of memory is requested, the pointer to it is added to the list, when released, then the corresponding pointer is removed from the list, to the end of the program to check the list to know that there is no memory leaks. The Visual Studio debugger and the C runtime (CRT) under the window platform use this principle to detect memory leaks.

When used in VS, you need to add

#define _crtdbg_map_alloc

#include <crtdbg.h>

The role of Crtdbg.h is to map the malloc and free functions to their debug versions _malloc_dbg and _free_dbg, which will track memory allocations and releases (valid in debug version)

_CrtDumpMemoryLeaks ();

The function will show the current memory leak, that is, the memory leak when the program runs to this line of code, and all the objects that are not destroyed will report a memory leak, so make this function as far as possible to the last.

For example:

#define _crtdbg_map_alloc#include <crtdbg.h> #include <iostream>using namespace std;int main (int Argc,char * * argv) {char *str1 = Null;char *str2 = null;str1=new char[100];str2=new char[50];d elete str1;_crtdumpmemoryleaks (); return 0;}

In the code above, the memory has requested two blocks, but only one piece is freed, and running debugging will be output in the outputs window:

Dumping objects
{136} normal block at 0x00084d70, bytes long.
Data: < > CD CD CD CD CD CD CD CD CDs CD CD
Object dump complete.

You can see that a memory leak is detected.

You can also use this method to detect memory leaks more complex, such as setting checkpoints and checking for memory leaks between checkpoints.

There are similar methods under Linux, which can be consulted as follows: Http://en.wikipedia.org/wiki/Mtrace

C + + memory leak and detection

Related Article

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.