简体   繁体   中英

Sending data issue TCP/IP

//------------------------------
    //creating dynamic array to send
    std::list<char> list;
    char in=NULL;
    while(1)
    {
        scanf("%c",&in);
        if(in=='\n') break;
        list.push_back(in);
    }
    //char *sendbuf=NULL;
    char* sendbuf=new char[list.size()]; // create a dynamic array   

        std::copy(list.begin(),list.end(),sendbuf); // copy the data 
        //sendbuf=array;
        iResult_send = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
        delete [] sendbuf; // destroy the dynamic array
        list.clear();
}
//-------------------------------------------

Hi all, I'm trying to send data to client through the dinamic array that i'm creating. when i sent data with static array char type the client got it just fine. but when i'm sending like that he is getting a lot of garbage after the message. Is there anything wrong with my array that i'm sneding?

iResult_send = send( ConnectSocket, sendbuf, (int)strlen(sendbuf) , 0 );

Message size determination is wrong. Try to use list.size() against it.

The problem is: your data is not null terminated, thus strlen() does not yield the correct size. (Presumably a way to big value).

correct is:

    iResult_send = send( ConnectSocket, sendbuf, sizeof(char) * list.size(), 0 );

btw: you can omitt the

        list.clear(); 
    }

the variable is destructed at the end of the block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM