killer
killer

Reputation: 121

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

I have program where I need to send a buffer to a socket. My question is can I delete the buffer immediately after I call the Winsock->send() method?

Reason why I brought up this quiestion: I used the Windbg tool for identifying memory leaks and it shows this place in BuildPacket(), new memory is not released properly. So I thought of clearing the memory after sending to sockets. This method will be called around 4,00,000 times which consumes most of the memory when my program is ran in multiple loops.

Pls. assume that m_ClientSocket is an already established socket connection.

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];
};

Please advice any possible solutions. Thank you.

Upvotes: 1

Views: 452

Answers (1)

Hatted Rooster
Hatted Rooster

Reputation: 36503

It's probably referring to your new in BuildPacket since you don't delete it but you do assign it to another pointer and that gets deallocated so it's most likely a false positive.

However, what's more problematic is that you have undefined behaviour in your code, namely:

void* ref = NULL;
delete ref;

It is undefined behaviour to call delete on a void*, you should cast it before deleting it.

Upvotes: 3

Related Questions