user1833852
user1833852

Reputation: 51

Resource leak in MFC SendMessage()

I am new to MFC.

How to release resource which is passed as (WPARAM) in SendMessage().

Here I using "new" to create for it. Following is the snapshot for same.

void Build::BuildCube()
{

    SCtPt *data = new SCtPt;
    data->vm = true;
    int dir = 100;
    MFrame()->SendMessage(WM_MAP_NEW, (WPARAM)data, (LPARAM) dir);
}

I want to make sure "data" resource get released of this function.

Thanks...

Upvotes: 0

Views: 698

Answers (3)

user2511124
user2511124

Reputation: 158

Did you consider writing the code like this:

void Build::BuildCube()
{
  SCtPt data;
  data.vm = true;
  int dir = 100;
  MFrame()->SendMessage(WM_MAP_NEW, (WPARAM)&data, (LPARAM)dir);
}

That way the data sent as WPARAM is still a pointer to your object, but when the application gets out of this method's scope, it will invoke the destructor and perform the cleanup for you.

Upvotes: 5

Jerry YY Rain
Jerry YY Rain

Reputation: 4382

As the SendMessage() API is a synchronous API, it sends the message to the other window procedure before returning. When the call to SendMessage() returns, then data can be freed/released:

void Build::BuildCube()
{
    SCtPt *data = new SCtPt;
    data->vm = true;
    int dir = 100;
    MFrame()->SendMessage(WM_MAP_NEW, (WPARAM)data, (LPARAM)dir);
    delete data;
}

Or, better yet, you can avoid allocating the data on the heap altogether. Simply allocate it on the stack and let RAII handle the rest:

void Build::BuildCube()
{
    SCtPt data;       // don't use "new", so you won't get a pointer
    data.vm = true;
    int dir = 100;
    MFrame()->SendMessage(WM_MAP_NEW, (WPARAM)data, (LPARAM)dir);
    // no delete necessary!
}

Upvotes: 3

Max
Max

Reputation: 3180

We usually do this :

At the point the data is allocated, the comment state explicitly where it will be deallocated.

void Build::BuildCube()
{

    SCtPt *data = new SCtPt; // Will be deallocated in handler of message WM_MAP_NEW
    data->vm = true;
    int dir = 100;
    MFrame()->SendMessage(WM_MAP_NEW, (WPARAM)data, (LPARAM) dir);
}

LRESULT CMainFrame::OnMapNew(WPARAM wParam, LPARAM )
{
  SCtPt *data = (SCtPt*) wParam;
  // do something with data;

  delete data;
}

Upvotes: 0

Related Questions