OnGetDayStateStart of CMonthCalCtrl and memory allocation

51 views Asked by At

The NMDAYSTATE states for prgDayState:

Address of an array of MONTHDAYSTATE values. The buffer at this address must be large enough to contain at least cDayState elements. The first element in the array corresponds to the date in stStart.

I asked ChatGPT and it is clearly wrong for this:

void CMyCalendar::OnGetDayState(NMHDR* pNMHDR, LRESULT* pResult)
{
    NMDAYSTATE* pDayState = reinterpret_cast<NMDAYSTATE*>(pNMHDR);
    // Allocate an array of MONTHDAYSTATE structures
    MONTHDAYSTATE* pDayStateArray = new MONTHDAYSTATE[pDayState->cDayState];
    // Assign the address of the array to the prgDayState member
    pDayState->prgDayState = pDayStateArray;
    // TODO: Add your control notification handler code here
    *pResult = 0;
    // Delete the prgDayState array
    delete[] pDayStateArray;
}

It suggests allocating dynamically but then says to delete it. The official docs does not make this clear about allocation / deallocation.

In my code I am using mdStates[4]{};.


I still have a fundamental issue here. On my PC it shows 2 calendras but on a clients PC it shows 3. So my mdState array is not large enough.

  • Should I be declaring the array with new based on cDayState.
    • Will the system own it?

As I expected, this causes memory leaks:

void CMeetingScheduleAssistantDlg::OnGetDayStateCalendarRange(NMHDR* pNMHDR, LRESULT* pResult)
{
    NMDAYSTATE      *pDayState = reinterpret_cast<NMDAYSTATE*>(pNMHDR);
    //MONTHDAYSTATE mdState[4]{}; // 1 = prev 2 = left 3 = right 4 = next
    MONTHDAYSTATE *mdState = new MONTHDAYSTATE[pDayState->cDayState];


    if (pDayState != nullptr)
    {
        const COleDateTime  datStart(pDayState->stStart);
        InitDayStateArray(pDayState->cDayState, &mdState[0], datStart);
        pDayState->prgDayState = &mdState[0];
    }

    if (pResult != nullptr)
        *pResult = 0;
}

At the moment I increased the size to 8 for the array and this prevents the crash and I have no memory leaks since not using new.

0

There are 0 answers