Access violation when the object goes out of scope in switch case

  c++, winapi

Ok, then. I started learning C++ and my task is to create a process manager with Win32 API. It is going to look like that:
https://i.stack.imgur.com/Qn90c.png

I have TBuffer class: (Buffer will keep information about the processes)

#pragma once

#include <wtypes.h>

#define BUFFER_SIZE 10
#define WM_UPDATELIST WM_USER

enum TProcessState { psEmpty, psNew, psRunning, psTerminated, psError };

struct TProcessInfo 
{
    TProcessState State;
    char Name[100];
    HANDLE Handle;
    int PID;
    int UserTime, KenelTime;
};

class TBuffer
{
private:
    HWND Wnd;
    CRITICAL_SECTION cs;
    TProcessInfo Buf[BUFFER_SIZE];
public:
    TBuffer(HWND AWnd);
    ~TBuffer();
    int Count();
    int AddProcess(char *AName);
    void Get(int Id, TProcessInfo &Pi);
    void Set(int Id, const TProcessInfo Pi);
    const char* ProcessStateToString(TProcessState state);
};

The class constructor has following realization:

TBuffer::TBuffer(HWND AWnd)
{
    Wnd = AWnd;
    InitializeCriticalSection(&cs);
    for (int i = 0; i < BUFFER_SIZE; i++)
    {
        Buf[i].State = psEmpty;
        Buf[i].Handle = 0;
        Buf[i].Name[0] = 0;
        Buf[i].PID = 0;
        Buf[i].UserTime = 0;
        Buf[i].Handle = 0;
    }
}

And destructor:

TBuffer::~TBuffer()
{
    DeleteCriticalSection(&cs);
}

The method using critical section:

void TBuffer::Set(int Id, const TProcessInfo Pi)
{
    EnterCriticalSection(&cs);
    ...
    LeaveCriticalSection(&cs);
}

In the main .cpp file I have global variable: TBuffer *Buffer;
And in the MainWndProc function where messages are processed in the case WM_INITDIALOG I am asked to create a TBuffer class object to initialize critical section and so on:

case WM_INITDIALOG:
{
    TBuffer Buf(hWnd);
    Buffer = &Buf;
    ...
    return TRUE;
}

My problem is that, as I read, class object after return TRUE is going out of scope and it’s destructor is called. That’s why the critical section is deleted and then other class methods like Set() and Get() are not able to enter critical section. So I’m looking for a way to leave the object in the scope. I think that something in WM_INITDIALOG is wrong with object creation.

By the way, when the WM_DESTROY message is processed I free the allocated memory for a global variable:

case WM_DESTROY:
    delete[] Buffer;
    PostQuitMessage(0);
    return TRUE;

Source: Windows Questions C++

LEAVE A COMMENT