我可以在使用 winsoc 发送缓冲区后删除内存吗?

Can I delete the memory after I send the buffer using winsoc?

本文关键字:删除 内存 缓冲区 winsoc 我可以      更新时间:2023-10-16

我有程序需要将缓冲区发送到套接字。我的问题是我可以在调用 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是未定义的行为,您应该在删除它之前强制转换它。