Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new in one thread and delete in another, not allowed?

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 output 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.

like image 272
Moberg Avatar asked Apr 09 '11 21:04

Moberg


1 Answers

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].

like image 166
Anthony Williams Avatar answered Sep 23 '22 15:09

Anthony Williams