A non-sense of memory disclosure

zhaozj2021-02-08  234

Electronic Science and Technology Zhu Ning

---- Recently, when writing a screen saver with VC , I found a problem that memory leaks was very confused. Later, on the basis of reference to several examples, this problem was solved. Let us analyze the causes and process methods:

---- The author has brought a sub-class CDrawWnd by CWND, adding the following code in the initInstance () of the main program class:

m_pmainwnd = new cdrawwnd ();

m_pmainwnd-> create (.....);

Return True;

---- After the debugging run, the VC debugger reports the memory leak. Obviously, the problem may only be on the first line of code above. When I started writing the above code, I also suspected that New didn't have a corresponding delete, which will cause the stack memory that cannot be recovered, but refer to the example "Hello" of VC 5.0, the code of this program is not different from the above, nor other functions Call the delete recycled the memory, but does not cause memory disclosure. Check the online help of VC , there is no detailed description, just talk to the closing window, automatically call the virtual function PostncDestory to reclaim M_PMainWnd points to the memory.

---- The author tried to call the delete m_pmainwnd in the destructor of the main program class, no effect. Explicit call CWnd :: DestoryWindow () does not work. Reference example Saver, found that the previous implementation code is exactly the same as the author, but it has been overloaded the PostncDestory virtual function in the CDRawWND class, where there is a line of key code:

DELETE THIS;

---- In fact, it destroy the CDrawWnd object.

- - I immediately modified my program, overloaded the PostncDestory function in the main window class, add the above speech, and immediately solve the problem of memory leakage.

---- The reason is finally understood. It turns out that if the program main window is inherited from CFraMewnd, the memory that is not required to use the memory, like the "Hello" example is such a program. But if you are directly inherited from the CWND class, you must consider this problem.

转载请注明原文地址:https://www.9cbs.com/read-1532.html

New Post(0)