mercredi 26 août 2020

Getting the error "CRT detected that the application wrote to memory after end of heap buffer" when deleting the structure pointer variable in C++

I have the below structure

.h file

 typedef struct _HID_DEVICE
    {
        PCHAR                   m_pcInputReportBuffer;
    } HID_DEVICE, *PHID_DEVICE;

PHID_DEVICE             m_pHidDevice;

I am using this structure variable (m_pHidDevice) and the member (m_pcInputReportBuffer) like as shown below in the implementation file

.cpp file

Initialization:

m_pHidDevice->m_pcInputReportBuffer =
        new char[ m_pHidDevice->m_hDeviceCaps.InputReportByteLength];

if( NULL == m_pHidDevice->m_pcInputReportBuffer )
    {
        throw exception("Memory could not be allocated");
    }
    memset(m_pHidDevice->m_pcInputReportBuffer,
           '\0', m_pHidDevice->m_hDeviceCaps.InputReportByteLength);

Destruction:

if (NULL != m_pHidDevice->m_pcInputReportBuffer )
    {
        delete []m_pHidDevice->m_pcInputReportBuffer;
        m_pHidDevice->m_pcInputReportBuffer = NULL;
    }

When it is calling delete in the if condition, I am getting the error "CRT detected that the application wrote to memory after end of heap buffer"

Here m_pHidDevice has some address but m_pcInputReportBuffer is blank (""). But the control is going into the if condition. How to restrict this?

Aucun commentaire:

Enregistrer un commentaire