【发布时间】:2017-05-16 11:08:06
【问题描述】:
我有程序需要将缓冲区发送到套接字。我的问题是我可以在调用 Winsock->send() 方法后立即删除缓冲区吗?
我提出这个问题的原因:我使用 Windbg 工具来识别内存泄漏,它在BuildPacket() 中显示了这个地方,新内存没有正确释放。
所以我想在发送到套接字后清除内存。
当我的程序在多个循环中运行时,此方法将被调用大约 4,00,000 次,这会消耗大部分内存。
请。假设m_ClientSocket 是一个已经建立的套接字连接。
bool TCPSendBuffer(char* pMessage, int iMessageSize)
{
try {
int iResult = 0;
iResult = send(m_ClientSocket, pMessage, iMessageSize, 0);
if (iResult == SOCKET_ERROR){
// Error condition
m_iLastError = WSAGetLastError();
return false;
}
else{
// Packet sent successfully
return true;
}
}
catch (int ex){
throw "Error Occured during TCPSendBuffer";
}
}
int BuildPacket(void* &pPacketReference)
{
TempStructure* newPkt = new TempStructure();
// Fill values in newPkt here
pPacketReference = newPkt;
return sizeof(TempStructure);
}
bool SendPackets()
{
void* ref = NULL;
bool sent = false;
int size = BuildPacket(ref);
sent = TCPSendBuffer((char*)ref, size);
// Can I delete the ref here...?
delete ref;
return sent;
}
struct TempStructure
{
UINT32 _Val1;
UINT32 _Val2;
UINT32 _Val3;
UINT32 _Val4;
UINT32 _Val5;
UINT32 _Val6;
UINT8 _Val7;
UINT16 _Val8;
UINT16 _Val9;
UINT16 _Val10;
UINT32 _Val11[16];
UINT32 _Val12[16];
bool _Val13[1024];
};
请提供任何可能的解决方案。谢谢。
【问题讨论】:
-
您可以而且必须在发送操作完成后删除缓冲区。在同步调用的情况下 - 就在函数返回之后。以防异步调用 - 通常在回调中,在操作完成时执行
标签: c++ windows sockets winsock