指针的内存分配/释放

时间:2014-08-26 09:28:46

标签: c++ visual-c++ free calloc

我有简单的套接字通信功能:

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;


}

我在线上有错误

free(dtx);

错误:

---------------------------
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   
    ---------------------------

此代码中的callocfree有什么问题?

1 个答案:

答案 0 :(得分:2)

您为这两个字符串的串联分配strlen(tx)+strlen("DATA ")个字节 - 其中是零终结符的字节?使用strlen(tx)+strlen("DATA ")+1