使用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 是未定义的行为,您应该在删除它之前转换它。