Search code examples
c++socketscharhextelnet

Hex in char array resulting in random character when writing to socket


When communicating with an external system they want me to add a null byte to the end of my response. However I'm facing some problems:

//reading from socket

//sending response
std::string response = "hardcodedResponse";
int bufferSize = response.size() + 1; // +1 for the trailing zero
char buffer[bufferSize];    

for (int i = 0; i < response.size(); i++)
{
    buffer[i] = response[i];
}

buffer[bufferSize] = 0x00;

int socketfd = 1;
unsigned bytesWritten = 0;

while (bytesWritten < bufferSize)
{
    bytesWritten += ::write(socketfd, buffer[bytesWritten], bytesToWrite - bytesWritten);
}

When I use telnet to send something to the socket, I do receive a response: "hardcodedResponse" followed by a ▒. I figured that made sense since 0x00 is null. However if I add 0x41 (A) to the end, I receive "hardcodedResponse" + a (seemingly) random character. If I print the last character of the buffer before writing to the socket, it does print 'A'. This wouldn't really matter if the external system would also receive the correct byte, but alas, they receive the random one.

I'm at a loss as to why this is happening. Hopefully someone can help me understand.


Solution

  • Aside from all the socket, look at the buffer length and where you put the null:

    std::string response = "hardcodedResponse";
    int bufferSize = response.size() + 1; // +1 for the trailing zero
    char buffer[bufferSize];    //Up to, but not including bufferSize
                                //0, 1, ... bufferSize-1
    
    for (int i = 0; i < response.size(); i++)
    {
        buffer[i] = response[i];
    }
    
    buffer[bufferSize] = 0x00;  //BOOM udefined behaviour
    

    You made one extra char for the null, not two, so put the null at the end not beyond the end.

    buffer[bufferSize-1] = 0x00;