我的程序是否因为我在一个线程中使用 new 并在另一个线程中使用删除而被中断?
我正在从 com 端口读取数据。由于我不知道数据何时到来,因此我在线程中连续读取。
当我读取了足够的字节时,我通过发布一条带有指向字符串的指针的消息来让主线程知道这一点:
msg[i] = '\0';
completeMsg = new char[i];
strcpy(completeMsg, msg);
PostMessage(hDlg, BT_MSG, NULL, (LPARAM) completeMsg);
i = 0;
主线程对此消息的响应是:
case BT_MSG:
{
char* msg = (char*) lParam;
ShowMsg(msg);
delete [] msg;
break;
}
但看起来不允许在该线程中删除,因为我得到了这个当我单步删除行时出错:
Windows 已触发断点 SPO.exe。
这可能是由于 堆,这表明 SPO.exe 中存在错误 或其已加载的任何 DLL。
这也可能是由于用户 当 SPO.exe 获得焦点时按 F12。
输出窗口可能有更多 诊断信息。
我应该使用一些全局变量还是发回消息让读取线程处理删除?它没有消息循环自动取款机,所以我不想为此添加一个。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您链接到编译器的多线程运行时库,您应该能够在一个线程中使用
new
并在另一个线程中使用delete
。然而,看起来你确实有缓冲区溢出。您使用
msg[i]=0
以 null 终止msg
,但只分配i
字节 --- 您可能需要new字符[i+1]。
You should be able to use
new
in one thread anddelete
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
withmsg[i]=0
, but only allocatei
bytes --- you probably neednew char[i+1]
.假设一切都正确同步,则可以删除在另一个线程上分配的内存。在您的情况下,您的 COM 端口线程在 PostMessage 之后不使用分配的指针,因此在主线程上删除就可以了。
所以,我想知道您是否遇到了与线程无关的“正常”堆损坏。问题可能出在
strcpy
上,具体取决于i
的含义。请记住,strcpy 将写入终止空字符。您可能想要: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 whati
means. Remember thatstrcpy
will write the terminating null character. You probably want: