[RESOLVED] Memory problem passing BYTE array to thread
I am trying to pass a BYTE array to a thread. This is done using the PostThreadMessage() function and passing the BYTE array as the WPARAM parameter and the number of bytes in the array as LPARAM parameter.
See below.
Code:
BYTE* pData = new BYTE(MB_REQ_BUFSIZE);
if(pData != NULL)
{
FillMemory(pData, MB_REQ_BUFSIZE, 0);
memcpy(pData, m_aRequest, MB_REQ_BUFSIZE);
m_pSerialWriter->PostThreadMessage(UWM_DATA_SEND, (WPARAM)pData, (LPARAM)MB_REQ_BUFSIZE);
}
In the OnDataSend() handler of the thread i want to retrieve the BYTE* from WPARAM and use it. This all works well, however when i try do delete the array in this handler a assertion message pops up saying "Damage after NORMAL block (#526) at 0x00ADBBC0".
Following this assertion takes me to DBGHEAP.c into the following code:
Code:
if (!CheckBytes(pbData(pHead) + pHead->nDataSize, _bNoMansLandFill, nNoMansLandSize))
_RPT3(_CRT_ERROR, "DAMAGE: after %hs block (#%d) at 0x%08X.\n",
szBlockUseName[_BLOCK_TYPE(pHead->nBlockUse)],
pHead->lRequest,
(BYTE *) pbData(pHead));
The way i try to delete the BYTE array is:
Code:
OnSendData(WPARAM wParam, LPARAM lParam)
{
BYTE* pData = (BYTE*)wParam;
int iNrBytes = (int)lParam;
...
delete[] pData;
}
Re: Memory problem passing BYTE array to thread
Code:
BYTE* pData = new BYTE(MB_REQ_BUFSIZE);
this allocates only one byte.
Guess you want
Code:
BYTE* pData = new BYTE[MB_REQ_BUFSIZE];
Kurt
Re: Memory problem passing BYTE array to thread
Wow, you are sharp! Thanx man!
Re: Memory problem passing BYTE array to thread
Also memory allocation and deallocation [for a specific] block should ALWAYS be done from the same thread.
Re: Memory problem passing BYTE array to thread
Also memory should always be allocated/released from the same thread. There is no guarentee that multiple threads will be using the same heap.
Re: [RESOLVED] Memory problem passing BYTE array to thread
CPUWizard, do you have a suggestion how i can allocate/deallocate the BYTE buffer in this case because PostThreadMessage() does not wait for completion.
Now i allocate memory in main thread, pass it to the workerthread and this will release memory as soon as it has done processing.
Re: [RESOLVED] Memory problem passing BYTE array to thread
You could WFSO (WaitForSingleObject) on the thread, check return code using GetExitCodeThread for success if so delete the memory in the main thread.