Im reading data from a com-port. Since I don't know when data is coming, I'm reading continuously in a thread.
When i have read enough bytes, I let the main thread know this by posting a message with a pointer to the string:
msg[i] = '\0';
completeMsg = new char[i];
strcpy(completeMsg, msg);
PostMessage(hDlg, BT_MSG, NULL, (LPARAM) completeMsg);
i = 0;
The main thread's response to this message is:
case BT_MSG:
{
char* msg = (char*) lParam;
ShowMsg(msg);
delete [] msg;
break;
}
But it looks like deleting in this thread isn't allowed because i get this error when I step the delete-line:
Windows has triggered a breakpoint in SPO.exe.
This may be due to a corruption of the heap, which indicates a bug in SPO.exe or any of the DLLs it has loaded.
This may also be due to the user pressing F12 while SPO.exe has focus.
The outp开发者_运维百科ut window may have more diagnostic information.
Should i use some global variable or send a message back to let the read-thread handle the deletion? It doesn't have a message-loop atm so I'd rather not add one just for this.
You should be able to use new
in one thread and delete
in another, provided you link against your compiler's multi-threaded runtime library.
However, it looks like you actually have a buffer overrun. You are null-terminating msg
with msg[i]=0
, but only allocate i
bytes --- you probably need new char[i+1]
.
It is okay to delete memory allocated on another thread assuming everything is properly synchronized. In your case, your COM port thread does not use the allocated pointer after PostMessage, so deleting is on the main thread is fine.
So, I'm wondering if you are getting a "normal" heap corruption that doesn't have anything to do with threading. The problem might be with the strcpy
depending on exactly what i
means. Remember that strcpy
will write the terminating null character. You probably want:
completeMsg = new char[i+1];
精彩评论