A non-sense of memory disclosure

zhaozj2021-02-11  213

A non-spot memory leak Electronic Technology University Zhu Nining - recently, when writing a screen saver with VC , discovered the problem of memory leaks, 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 derived a subclass CDRawwnd by CWND, adding the following code in the initInstance () of the main program class: m_pmainwnd = new cdrawwwwwwwwnd ();

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. View VC online help, there is no detailed explanation, just when the window is turned off, the virtual function PostncDestory reclaim memory M_PMainWnd pointing to the memory. --- The author tried to call 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 identical to the author, but it has heavy loaded 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-4034.html

New Post(0)