How to Prevent Memory leakage in Windows

Source: Internet
Author: User

Develop C ++ in WindowsProgramWe often need to use malloc to apply for memory and use free to recycle the memory. However, developers may accidentally forget to free the memory, which leads to memory leakage.

1. Use the database to detect memory leakage Information

 
# Define_ Crtdbg_map_alloc // without this macro definition, we can only know where the memory is leaked, but cannot know where to apply for the memory and forget to release it.# Include<Stdlib. h># Include<Crtdbg. h>IntMain (Void){Char* P = (Char*) Malloc (Sizeof(Char)*100); _ Crtdumpmemoryleaks ();}

It is very easy to use crtdbg to detect memory leakage, as long as _ crtdbg_map_alloc is defined in the first line of the file, and then include the header file crtdbg. h. Call _ crtdumpmemoryleaks where the program requires memory detection to output Memory leakage information. For the above program, we applied for 100 bytes of memory instead of being released, however, we can clearly see where the memory is leaked, as shown in figure

We applied for memory in row 8 of the Main. cpp file, but did not release it.

So how does the compiler know that we have memory leakage ?? The macro definition is used to replace the called malloc with the _ malloc_dbg in the crtdbg library. When we apply for memory, _ malloc_dbg will first record the number of rows and size of the applied memory (remember that the compiler has a built-in macro definition _ line _ and _ file _ No ?), Put the information in a list (for example, it is very slow to use list to save the information once the program grows). When we use free memory, delete the memory from the list. When we call _ crtdumpmemoryleaks (), the list information is printed in sequence.

The following is the actual called malloc prototype after _ crtdbg_map_alloc is defined. malloc has become a macro definition.

 
# DefineMalloc (s) _ malloc_dbg (S, _ normal_block, _ file __, _ line __)

Of course, we generally call _ crtdumpmemoryleaks at the end of the program. If our program has multiple exits, we need to call _ crtsetdbgflag (_ crtdbg_alloc_mem_df | _ crtdbg_leak_check_df) at the beginning of the program.

 

Sometimes we need to checkCodeWhether Memory leakage exists. The crtdbg library can also help us.

 
_ Crtmemstate S1; _ crtmemstate S2; _ crtmemcheckpoint (&S1 );Char* P2 = (Char*) Malloc (400); _ Crtmemcheckpoint (&S2); _ crtmemstate S3;If(_ Crtmemdifference (& S3, & S1 ,&S2) {_ crtmemdumpstatistics (&S3 );}

In this way, the memory usage information between S1 and S2 is displayed in the output window:

0 bytes in 0 free blocks.
400 bytes in 1 normal blocks.
0 bytes in 0 CRT blocks.
0 bytes in 0 ignore blocks.
0 bytes in 0 client blocks.
Largest number used: 0 bytes.
Total allocations: 400 bytes.

 

The crtdbg Library also has disadvantages. When you use a lib or dll library provided by someone else, you call this function, which is allocated with memory, you need to call another function to release the memory, but you do not know that this function needs to call another function to release the memory, which cannot be detected by the crtdbg library, this function includes C ++'s new function, so this library does not actually apply to C ++

 

2. Use cmd_ptr to manage memory

If you have used the boost library, you should know that there is a shart_ptr in boost, which is known as an artifact, because it can help us automatically manage the memory. The specific usage is simple:

 
Boost: shared_ptr <connection> P (NewConnection ());

In this case, we do not need to delete the memory. shartd_ptr will help us Delete the memory when we do not need the fast memory. shartd_ptr uses the reference count and the raiI of C ++ internally, when another object references this pointer, the reference technology is + 1. When the shartd_ptr destructor calls the reference count is-1. When the value is 0, the pointer is deleted, therefore, we do not need to call Delete to release resources. mongo_ptr will help us manage

 

Although shared_ptr looks very easy to use, shared_ptr still becomes complicated once the program is complicated (four sins of shared_ptr). Of course, boost itself is complicated, this is one reason why I do not like boost.

 

3. Centralized Resource Management

This is also a frequently used method, especially in the use of large programs. In combination with the single-piece mode, resources are centrally managed in the entire program or module, in this way, when the program ends, as long as we clean up these resources in the destructor, we can avoid Memory leakage. All write operations on data are performed in this class in a unified manner, to expose internal data, only the const data is provided externally (the const attribute can be removed through strong conversion)

Of course, this method is not applicable to all scenarios. For example, if we need to provide a database to others, we cannot predict what operations the customer needs. Therefore, this method is only applicable to internal team development.

 

In short, there is still no good solution to memory management as far as I know. Especially when the Code expands, it seems that Java, Python, and Erlang all have memory leakage problems, we can only pay more attention to it in normal development.

 

References:

Chen Shuo's blog (there are some shared_ptr materials. It can be seen from here that shared_ptr is not that easy to use)

Shared_ptr: Four sins

Msdn crtdbg Library

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.