Click here to Skip to main content
15,915,319 members
Please Sign up or sign in to vote.
1.60/5 (3 votes)
See more:
Hello, in my MFC C++ program my compiler detected memory leaks. I use CDC* pDC; and CBitmap* Bitmap; in my header file and then in OnInitDialog() i use: pDC = new CDC; and Bitmap = new CBitmap;. My compiler detected these as a memory leak. What might be the problem? Thanks in advance!
Posted

That is correct. Edit your post to add detail, don't post fake answers to yourself.
 
Share this answer
 
THe problem is obvious. You never delete them. If they are used throughout the program, and this dialog is always visible, then it's not really a problem, but you should still get in the practice of cleaning up all member variables in your destructor.
 
Share this answer
 
you are using
pDC = new CDC; and Bitmap = new CBitmap;

use keyword "delete" to free them.
 
Share this answer
 
Add an event handler for the WM_DESTROY windows message, then add the lines below inside it:

C++
if (pDC != NULL) delete pDC;
if (Bitmap != NULL) delete Bitmap;


Be aware that if you select your bitmap onto the device context, i.e. pDC->SelectObject(Bitmap), you should save the pointer to the CBitmap returned by the method call and restore it onto the device context before deleting it, as shown below:


  1. Add the following members to your class:
    C++
    CDC *pDC;
    CBitmap *pBitmap;
    CBitmap *pOldBitmap;

  2. Add the following lines to the OnInitDialog method of your class:
    C++
    pOldBitmap = NULL;
    pDC = new CDC;
    if (pDC != NULL && pDC->CreateCompatibleDC(GetDC()))
    {
       pBitmap = new CBitmap;
       if (pBitmap != NULL && pBitmap->CreateCompatibleBitmap(pDC, 640, 480))
       {
          pOldBitmap = pDC->SelectObject(pBitmap);
       }
    }

  3. Add the following lines to the OnDestroy method of your class:
    C++
    if (pOldBitmap != NULL) pDC->SelectObject(pOldBitmap);
    if (pDC != NULL) delete pDC;
    if (pBitmap != NULL) delete pBitmap;

 
Share this answer
 
v2
So, i have a dialog window that doesn't have destructor by default. The only way is to add one. For example if my class is called Game in Game.h I have to type virtual ~Game() and in CPP file - Game::~Game(). Is that true?
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900