In VC++ Notification Callbacks Can NMHDR* be NULL?

Viewed 61

Below is some sample code taken from https://docs.microsoft.com/en-us/cpp/mfc/reference/clistctrl-class?view=vs-2019. In all examples I have seen it is not checking if NMHDR* is null or not. Can it be null or is it guaranteed not to be null?

void CListCtrlDlg::OnDblClk(NMHDR* pNMHDR, LRESULT* pResult)
{
    UNREFERENCED_PARAMETER(pResult);
    LPNMITEMACTIVATE pia = (LPNMITEMACTIVATE)pNMHDR;
    LVHITTESTINFO lvhti;

    // Clear the subitem text the user clicked on.
    lvhti.pt = pia->ptAction;
    m_myListCtrl.SubItemHitTest(&lvhti);

    if (lvhti.flags & LVHT_ONITEMLABEL)
    {
        m_myListCtrl.SetItemText(lvhti.iItem, lvhti.iSubItem, NULL);
    }
}
1 Answers

If a handler such as the CListCtrlDlg::OnDblClk function you have shown is called by the MFC Framework, in response to the relevant WM_NOTIFY message, then the NMHDR* parameter will not be NULL.

However, it is possible to call such a handler function manually, in which case that parameter can have any value the calling code(r) cares to give it.

So, in terms long-term safety and/or maintenance - especially when working with codebases accessed and/or modified by other programmers, over whom you have little or no control - you may wish to check the validity of the pointer.

Related