Search code examples
c++visual-c++freecalloc

Memory allocation/deallocation for pointer


I have simple socket communicate function:

int communicate( const char * tx, char * rx, int bufSize , char * inetAddr, int port )
{
    if (!sockInitialised) initSock();

    if (sockInitialised)
    {
        SOCKET s;
        struct sockaddr_in server;

        server.sin_addr.s_addr = inet_addr(inetAddr);
        server.sin_family = AF_INET;
        server.sin_port = htons( port );

        if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
        {
            BOOST_LOG_SEV(getDefLg(), debug) << "Could not create socket : " << WSAGetLastError();
        } else
        {
            if (connect(s , (struct sockaddr *)&server , sizeof(server)) < 0)
            {
                puts("connect error");
                return 1;
            } else
            {
                int l =strlen(tx)+strlen("DATA ");

                char* dtx ;
                dtx = (char*) calloc(sizeof(char),strlen(tx)+strlen("DATA "));

                sprintf(dtx,"DATA %s",tx);

                if( send(s , dtx , strlen(dtx) , 0) < 0)
                {
                    puts("Send failed");
                    return 1;
                } else
                {

                    int recv_size = 0;
                    if((recv_size = recv(s , rx , bufSize , 0)) == SOCKET_ERROR)
                    {
                        puts("recv failed");
                    } else
                    {
                        rx[recv_size] = '\0';
                    }
                }
                free(dtx);
            }
        }
    } else return 1;


}

I have error on line

free(dtx);

Error:

---------------------------
Microsoft Visual C++ Debug Library
---------------------------
Debug Error!


    HEAP CORRUPTION DETECTED: after Normal block (#1497) at 0x057D26F8.
    CRT detected that the application wrote to memory after end of heap buffer.


    (Press Retry to debug the application)
    ---------------------------
    Abort   Retry   Ignore   
    ---------------------------

What is wrong with calloc and free in this code?


Solution

  • You allocate strlen(tx)+strlen("DATA ") bytes for concatenation of those two strings - where is the byte for zero terminator? Use strlen(tx)+strlen("DATA ")+1.