Memory leakage (1) [Z]

Source: Internet
Author: User
For a C/C ++ programmer, memory leakage is a common and troublesome problem. Many technologies have been developed to address this problem, such as smart pointer and garbage collection. The smart pointer technology is relatively mature. STL already contains classes that support smart pointer, but it does not seem to be widely used and cannot solve all the problems; garbage collection technology has been relatively mature in Java, but its development in the C/C ++ field is not smooth. Although some people have long thought about adding GC support to C ++. The real world is like this. As a C/C ++ programmer, memory leakage is always in your heart. Fortunately, there are many tools that can help us verify the existence of memory leaks and find out the problematic code.

 Memory leakage Definition

Generally, memory leakage refers to heap memory leakage. Heap memory refers to the memory allocated by the program from the heap, which is of any size (the size of the memory block can be determined during the running period). The released memory must be displayed after use. Applications generally use functions such as malloc, realloc, and new to allocate a block of memory from the heap. after use, the program must call free or delete to release the block. Otherwise, this memory cannot be used again, so we can say this memory is leaked. The following applet demonstrates heap memory leakage:

Void myfunction (INT nsize)

{

Char * P = new char [nsize];

If (! Getstringfrom (p, nsize )){

MessageBox ("error ");

Return;

}

... // Using the string pointed by P;

Delete P;

}
 Example 1

When the getstringfrom () function returns zero, the memory pointed to by the pointer P will not be released. This is a common case of Memory leakage. The program allocates memory at the entrance and releases the memory at the exit. However, the C function can exit from anywhere. Therefore, a memory leak may occur if a certain exit does not release the memory that should be released.

Broadly speaking, memory leaks include not only heap memory leaks, but also system resource leaks, such as core handle, GDI object, socket, and interface, basically, these objects allocated by the operating system also consume memory. If these objects are leaked, memory leakage will eventually occur. In addition, some objects consume core-state memory, which causes instability of the entire operating system when such objects are seriously leaked. Therefore, the system resource leakage is more serious than the heap memory leakage.

The leakage of GDI object is a common resource leakage:

Void cmyview: onpaint (CDC * PDC)

{

Cbitmap BMP;

Cbitmap * poldbmp;

BMP. loadbitmap (idb_mybmp );

Poldbmp = PDC-> SelectObject (& BMP );

...

If (something ()){

Return;

}

PDC-> SelectObject (poldbmp );

Return;

}
 Example 2

When something () returns a non-zero value, the program does not select poldbmp back to PDC before exiting. This will cause the hbitmap object pointed to by poldbmp to leak. If this program runs for a long time, the entire system may be blurred. This problem is easily exposed in Win9x, because the GDI Heap of Win9x is much smaller than that of Win2k or NT.

Memory leakage occurs in the following ways:

Memory leakage can be classified as follows:

1. Frequent Memory leakage. Code with Memory leakage will be executed multiple times, resulting in a memory leak each time it is executed. For example, if the something () function returns true all the time, the hbitmap object pointed to by poldbmp always leaks.

2. Occasional Memory leakage. Memory leakage occurs only in certain environments or operations. For example, if the something () function returns true only in a specific environment, the hbitmap object pointed to by poldbmp does not always leak. The frequency and frequency are relative. For a specific environment, unexpected events may become frequent. Therefore, the test environment and test method are crucial for detecting memory leaks.

3. One-time memory leakage. The code with Memory leakage is executed only once, or due to algorithm defects, there will always be only one piece of Memory leakage. For example, the class constructor allocates the memory, but the memory is not released in the destructor. However, because the class is a Singleton, the memory leakage only occurs once. Another example:

Char * g_lpszfilename = NULL;

Void setfilename (const char * lpcszfilename)

{

If (g_lpszfilename ){

Free (g_lpszfilename );

}

G_lpszfilename = strdup (lpcszfilename );

}
Example 3

If the program does not release the string pointed to by g_lpszfilename at the end, even if setfilename () is called multiple times, there will always be one piece of memory, and only one piece of memory will leak.

4. Implicit Memory leakage. The program continuously allocates memory during the running process, but it does not release the memory until it ends. Strictly speaking, there is no memory leakage because the program releases all requested memory. However, if a server program needs to run for several days, weeks, or even months, failing to release the memory in time may eventually exhaust all the system memory. Therefore, we call this type of Memory leakage an implicit memory leak. For example:

Class connection

{

Public:

Connection (socket S );

~ Connection ();

...

PRIVATE:

Socket _ socket;

...

};

Class connectionmanager

{

Public:

Connectionmanager (){

}

~ Connectionmanager (){

List : Iterator it;

For (IT = _ connlist. Begin (); it! = _ Connlist. End (); ++ it ){

Delete (* it );
}

_ Connlist. Clear ();

}

Void onclientconnected (socket s ){

Connection * P = new connection (s );

_ Connlist. push_back (P );

}

Void onclientdisconnected (connection * pconn ){

_ Connlist. Remove (pconn );

Delete pconn;

}

PRIVATE:

List _ Connlist;

};

Example 4

If the server does not call the onclientdisconnected () function after the client is disconnected from the server, the connection object of the connection will not be deleted in time (when the server program exits, all connection objects will be deleted in the onmanager destructor ). Implicit Memory leakage occurs when connections are established and disconnected constantly.

From the perspective of user programs, memory leakage does not cause any harm. As a general user, the memory leakage does not exist. The real danger is the accumulation of Memory leakage, which will eventually consume all the memory of the system. From this point of view, one-time memory leakage is not harmful because it will not accumulate, while implicit memory leakage is very harmful, because it is more difficult to detect than frequent and occasional memory leaks.

Trackback: http://tb.blog.csdn.net/TrackBack.aspx? Postid = 222999

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.