Memory leakage detection

Source: Internet
Author: User
The author of Memory Leak Detection (self-written)
Keyword Memory leakage memory debug heap
Original Author name is very earthy
The original source of the article is self-written

Introduction
It briefly explains how to use the tool in the VC library to check the memory leakage of the Code.

Reader rating 8 rating 2

Body
Memory leakage detection

I. Memory leakage
Memory leakage is a common problem in programming. memory leakage is often manifested in a strange way, basically every program shows a different way. however, generally, there are only two final results. One is when the program fails. one is insufficient system memory. another method is that the intermediate result program is not suitable, but the system's response time is significantly reduced. It will be normal only after a scheduled reboot.

There is a simple way to check whether a program has memory leakage. windows Task Manager is used ). run the program and check "memory usage" and "virtual memory size" in the task manager. After the program requests the memory required by the program, if the virtual memory continues to grow, it indicates that the program has a memory leakage problem. of course, if the number of memory leaks is very small, it may take a long time to see this method.

Of course, the simplest method is probably to use tools such as compuware's boundchecker to detect, but the prices of these tools are a little extravagant for individuals.

If it is a released program, it is time-consuming and laborious to check whether there is memory leakage. Therefore, the memory leakage should be checked at any time during the code generation process.
Ii. Cause
Memory leakage is generally caused by three reasons: 1. I forgot to recycle the allocated memory. 2. there is a problem with the program code, resulting in no way to recycle. 3. some API function operations are incorrect, causing memory leakage.
1. memory has forgotten to be recycled. This is not the case. but it is also a common problem in code. after the memory is allocated, it must be recycled after use. if this function is not recycled, the memory leakage will occur. If the code leaked by the memory is frequently called, the memory leakage will increase. this affects the operation of the entire system. for example, the following code
For (Int = 0; I <100; I ++)
{
Temp = new byte [2, 100];
}
100 * bytes of Memory leakage will occur.
2. In some cases, some memory may fail to be recycled due to code writing problems. For example, the following code
Temp1 = new byte [2, 100];
Temp2 = new byte [100];
Temp2 = temp1;
In this way, the memory address of temp2 is lost and cannot be recovered. At this time, there is no way to recycle the memory space of temp2.

3. improper application of API functions. Some special APIs, such as formatmessage, are provided in windows. if format_message_allocate_buffer is included in the parameter, it will generate a new memory buffer in the function. however, you need to call localfree to release this buffer. if you forget, memory leakage will occur.

Iii. Check Methods

The general memory leak check is indeed very difficult, but it is not completely impossible. if you use the VC library to write things, you are lucky to have a lot of tools to check for Memory leakage, but you just don't want to use it. the C Runtime Library of the debug version of Visual C ++ ). it has provided several functions to help you diagnose your code and track memory leaks. in addition, the most convenient part is that these functions do not play any role in the release version, which will not affect the running efficiency of your release version program.
For example, the following example shows a detailed memory leakage. of course, if there are only a few lines of code, it is easy to see that there is a memory leak. however, it is not that easy to check for Memory leakage in thousands of lines of code.
Char * pstr = new char [5];
Lstrcpy (pstr, "memory leak ");
If we perform heap operations in the debug version code, including malloc, free, calloc, realloc, new, and delete can use the heap debug function in the VC debug Runtime Library for heap integrity and security checks. for example, in the above Code, the lstrcpy operation obviously destroys the pstr Heap Structure. it overflows and destroys neighboring data. then we can add the _ crtcheckmemory function to the code after calling lstrcpy. the _ crtcheckmemory function finds that the previous lstrcpy causes the heap structure of the pstr to be damaged and outputs such a report:
Emory check error at 0x00372fa5 = 0x79, shocould be 0xfd.
Memory check error at 0x00372fa6 = 0x20, shocould be 0xfd.
Memory check error at 0x00372fa7 = 0x6c, shoshould be 0xfd.
Memory check error at 0x00372fa8 = 0x65, shocould be 0xfd.
Damage: after normal block (#41) at 0x00372fa0.
Normal located at 0x00372fa0 is 5 bytes long.
It indicates that the length of pstr should be 5 bytes, but several bytes after 5 bytes are also illegally rewritten, reminding you to initiate out-of-bounds operations.
_ Crtcheckmemory only returns true and false values. You can use _ asserte () to report error information. the preceding statement can be changed to _ asserte (_ crtcheckmemory (). In this way, a warning dialog box is displayed when the debug program is running, in this way, you do not have to keep staring at the output window during running. at this time, press retry to start source code debugging. let's see where the problem is.

Figure 1
Other similar functions include _ crtdbgreport, _ blank, _ crtismemoryblock, _ crtisvalidpointer, _ crtmemcheckpoint, _ crtmemdifference, _ blank, _ blank, _ crtsetallochook, _ crtsetbreakalloc, _ crtsetdbgflag, _ crtsetdumpclient, _ crtsetreportfile, _ crtsetreporthook, _ crtsetreportmode
All these functions can be used to check the memory usage in the debug version. The usage of these functions is not described here. You can check msdn.
Among these functions, the function is very useful, or the function with a high usage is that _ crtmemcheckpoint sets a memory checkpoint. this function gets the running status of the current memory. _ crtmemdifference checks the differences between the two memory states. _ crtmemdumpallobjectssince indicates the information of objects in the heap starting from the running of the program or from a memory checkpoint. also, _ crtdumpmemoryleaks dumps out the memory information in the heap when memory overflow occurs. _ crtdumpmemoryleaks are generally called after code suspected to be Memory leakage. For example
# Include <windows. h>
# Include <crtdbg. h>
Void main ()
{
Char * pstr;
Pstr = new char [5];
_ Crtdumpmemoryleaks ();
}
Output:
Detected memory leaks! À remind you that the Code has memory leakage.
Dumping objects->
{44} normal block at 0x00372db8, 5 bytes long.
Data: <> CD
Object dump complete.
If you double-click the output row containing the row file name, the pointer will jump to the row where the memory is allocated in the source file.
When we cannot determine which code causes memory leakage, we need to compare the memory status. set a memory check point before and after a suspicious code segment to check whether the memory usage has changed. to determine whether memory leakage exists. therefore, we need to define three _ crtmemstate objects to save the memory state to be compared. the two are used for comparison. One is used to save the difference between the first two.
_ Crtmemstate sh1, SH2, sh_diff;
Char * pstr1 = new char [100];
_ Crtmemcheckpoint (& sh1);-> set the first memory checkpoint
Char * pstr2 = new char [100];
_ Crtmemcheckpoint (& SH2);-> set the second memory checkpoint
_ Crtmemdifference (& sh_diff, & sh1, & SH2);-> check for changes
_ Crtmemdumpallobjectssince (& sh_diff);-> dump changes

If your program uses the MFC class library, the memory leakage check method is quite simple. because the debug version of MFC itself provides part of the Memory leakage check. most new and delete memory leaks are generated because they are not paired. MFC generates reports. this is mainly because MFC reloads the new and delete operators of the debug version. in addition, the previously mentioned API functions are repackaged. in the MFC class library, the class that checks for Memory leakage is called cmemorystate. It repacks the functions of _ crtmemstate, _ crtmemcheckpoint, _ crtmemdifference, and _ crtmemdumpallobjectssince. other functions are provided with functions starting with afx for the use of MFC programs such as afxcheckmemory and afxdumpmemoryleaks. cmemorystate and related functions are defined in afx. h In the header file. there is a simple way to track the declarations of these functions. find the following code in the MFC program code in VC, usually in X. starting part of CPP
# Ifdef _ debug
# Define new debug_new
# UNDEF this_file
Static char this_file [] = _ file __;
# Endif
Move the cursor over debug_new and press F12 to enter afx. h defines the code of these classes and functions. the general check method for Memory leakage in VC is mainly the above two methods. of course, these two methods are only for the heap check of the debug version. if there is a memory leak in the release version, it will be a lot of trouble to check.
4. Conclusion:
In fact, the heap memory leakage problem is quite good. the check tools provided by VC are not very small, but if there is any problem with the stack, I am afraid it will be a lot of trouble. stack problems generally do not cause memory leakage, but your code may have a logical impact. this is the most painful thing. programming is to be careful and be careful.
(This Article is not finalized and is being modified. The diagram in this article is limited to the column restrictions to remove, but does not affect reading)

The final completion time is noon

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.