简体   繁体   中英

C++ TCP socket garbage value

I have my socket comms pretty much working. The only thing that I'm not sure about is why I'm getting some garbage values at the end of my message. The first message I send contains some extra characters at the end, and every message after that is as expected...does anyone have any insight as to why this is happening?

Send:

CString string = "TEST STRING TO SEND";
char* szDest;
szDest = new char[string.GetLength()];
strcpy(szDest,string);
m_pClientSocket->Send(szDest,strlen(pMsg));

Receive: (this is using Qt)

char* temp;
int size = tcpSocket->bytesAvailable();
temp = new char[size];
tcpSocket->read(temp,size);

You will be missing the \\0 in your temp after read, since it's not really transmitted (and probably shouldn't be)

You likely need to change the receive a little bit:

temp = new char[size + 1];
int realSize = tcpSocket->read(temp, size);
temp[realSize] = 0;

Btw, you would be better off with QTcpSocket::readAll() in this little snipped.

I don't know this CString class, but I see two bugs here:

  • Does GetLength() include the terminating NUL? If not, your char buffer is one byte smaller than it needs to be, and the strcpy is clobbering memory after the end of the buffer.
  • strlen(pMsg) is the length of something other than szDest . This is probably the immediate cause of your problem.

The char buffer appears to be unnecessary: why don't you just do

CString string = "TEST STRING TO SEND";
m_pClientSocket->Send(string, string.GetLength());

?

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