CHtmlView leaks memory if you do not release BSTRs in several methods
Article ID | : | 241750 |
Last Review | : | November 21, 2006 |
Revision | : | 3.1 |
This article was previously published under Q241750
SYMPTOMS
The following methods in
CHtmlView cause a memory leak if called:
• | Navigate |
• | GetFullName |
• | GetType |
• | GetLocationName |
• | GetLocationURL |
• | LoadFromResource(LPCTSTR lpszResource) |
• | LoadFromResource(UINT nRes) |
CAUSE
This problem is caused by bugs in the internal implementation in the first five functions listed in the "Summary" section.
SysFreeString must be called in the first five functions on the allocated
BSTRs. The last two functions cause a leak because
CHtmlView::Navigate is called in both of these functions and
CHtmlView::Navigate causes a leak.
RESOLUTION
To work around the leak, the functions listed in the "Summary" must be implemented in each class derived from
CHtmlView. If you have several views derived some
CHtmlView, consider making a new base class, such as
CFixHtmlView, from CHtmlView, and then deriving the rest of the views from
CFixHtmlView instead of
CHtmlView:
1. | Inside the MFC application project, insert a new class. On the Insert menu, click New Class. In the New Class dialog box, make sure the Class Type is set to MFC Class. |
2. | Name the class CFixHtmlView, and then set the Base Class combo-box item to CHtmlView. |
3. | In the FixHtmlView.h file, add the following code to the class: class CFixHtmlView : public CHtmlView |
4. | In the FixHtmlView.cpp file, add the following code: //new code |
5. | In each of the CHtmlView-derived classes' header and source files, change all the code that refers to CHtmlView to CFixHtmlView. To assist with this task, on the Edit menu, click Replace. |
6. | Be sure to add the following line of code in each of the CHtmlView-derived classes' header files before the class declaration: #include "FixHtmlView.h" //Add me before the class declaration. |
7. | Rebuild the project. |
STATUS
Microsoft has confirmed that this is a bug in the Microsoft products that are listed in the "Applies to" section.
MORE INFORMATION
Steps to reproduce the behavior
1. | Create a new MFC SDI Application using AppWizard. Name it TestLeak1. |
2. | On Page 1 of AppWizard, change the Base class from CView to CHtmlView, and then click Finish. |
3. | Click the ResourceView tab and add a new menu item for the menu resource IDR_MAINFRAME. Add the item under the Help menu and change the caption to Test. |
4. | Use Class Wizard to add a COMMAND handler for the new menu item ID_HELP_TEST. Make sure that the class that handles the item is your CTestLeak1View class. |
5. | Add the following code to the handler: void CTestLeak1View::OnHelpTest() |
6. | Build the project. |