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

Im reading data from a port. Since I do not know when the data arrives, I constantly read the stream.

When I read enough bytes, I will let the main thread know about it by posting a message with a pointer to the line:

msg[i] = '\0'; completeMsg = new char[i]; strcpy(completeMsg, msg); PostMessage(hDlg, BT_MSG, NULL, (LPARAM) completeMsg); i = 0; 

The main thread response to this message:

 case BT_MSG: { char* msg = (char*) lParam; ShowMsg(msg); delete [] msg; break; } 

But it seems that deleting this thread is not allowed, because I get this error when I find the delete line:

Windows called a breakpoint in SPO.exe.

This may be due to a bunch of corruption, which indicates an error in SPO.exe or any of the downloaded dll files.

It may also be due to the user pressing F12 when SPO.exe has focus.

The output window may contain more diagnostic information.

Should I use some global variable or send a message back to allow read-thread to handle deletion? It does not have a message loop, so I do not want to add it just for this.

+4
source share
2 answers

You can use new in one thread and delete in another, provided that you reference your multi-threaded compiler runtime library.

However, it looks like you actually have a buffer overflow. You end with msg zero with msg[i]=0 , but only select i bytes --- you probably need new char[i+1] .

+4
source

You can delete the memory allocated in another thread, provided that everything is correctly synchronized. In your case, the COM port thread does not use the designated pointer after PostMessage, so deleting on the main thread is fine.

So, I am wondering if you are getting β€œnormal” cumulus damage that has nothing to do with streaming processing. The problem may be in strcpy depending on what i means. Remember that strcpy will write a terminating null character. You probably want:

 completeMsg = new char[i+1]; 
+2
source

Source: https://habr.com/ru/post/1347392/


All Articles