我可以在使用 winsoc 发送缓冲区后删除内存吗?
Can I delete the memory after I send the buffer using winsoc?
我有程序需要将缓冲区发送到套接字。我的问题是我可以在调用 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];
};
请告知任何可能的解决方案。谢谢。
它可能指的是您在BuildPacket
中的new
,因为您没有delete
它,但您确实将其分配给另一个指针并被释放,因此它很可能是误报。
但是,更成问题的是代码中有未定义的行为,即:
void* ref = NULL;
delete ref;
在void*
上调用delete
是未定义的行为,您应该在删除它之前强制转换它。
相关文章:
- 在c++中删除内存失败
- delete[]有问题,如何部分删除内存
- 在这种情况下,我必须删除内存吗?
- STD分配器是否会在堆上动态分配内存?它可以安全地删除内存吗?
- 我可以在使用 winsoc 发送缓冲区后删除内存吗?
- 最好的方法是删除内存泄漏
- com,删除内存,而不是调用版本()
- 如何调用返回后删除[]内存
- 删除内存空间后,指针的值保持不变还是更改?对象内容是否将被更改
- unique_ptr的矢量未被完全删除(内存泄漏)
- 在析构函数中安全地删除内存
- (C++) list.error 方法和使用指针删除内存
- 为结构C++中的指针分配和删除内存
- 正在读取指向已删除内存未定义行为的指针
- 何时会在单一实例中删除内存
- 删除内存时遇到困难
- 在 go 中删除内存
- 在C++中使用智能指针分配和删除内存的有效方法
- Cpp删除内存
- 手动调用析构函数后如何删除内存