cserial-portgtk

String brokes after splitted in C


I'm creating a serial port reader program using the GTK API with C. I'm encountering an issue where the original string received from the serial port loses its first character after splitting it into substrings.

while (1) {
    memset(buffer, 0, sizeof(buffer));
    int len = read(fd, buffer, sizeof(buffer)-1);
    if (len > 0) {
        buffer[len] = '\0';
        printf("Received: %s\n", buffer);


        char splittedBuffer[5][1024];

        int dataIndex = 0;
        int bufferIndex = 0;
        
        printf("len is %d\n", len);

        for (int i = 0; i < len; i++){
            if(buffer[i] == ';'){
                
                splittedBuffer[dataIndex][bufferIndex] = '\0';
                dataIndex ++;
                bufferIndex = 0;
                
            }else{
                splittedBuffer[dataIndex][bufferIndex] = buffer[i];
                bufferIndex++;

            }

            
        }

        printf("data0 : %s\n",splittedBuffer[0]);
        printf("data1 : %s\n",splittedBuffer[1]);
        printf("data2 : %s\n",splittedBuffer[2]);
        printf("data3 : %s\n",splittedBuffer[3]);
        printf("data4 : %s\n",splittedBuffer[4]);

        printf("after op: %s\n", buffer);
        
        
        

        
    } else if (len < 0) {
        perror("Error reading from serial port");
    }
}

(If you'd like to see the complete code, please feel free to ask it in the comments.)

I'd appreciate any insights into why the first character is disappearing after splitting.

and the output is;

Received: 23;10;20;30;40;

len is 16
data0 : 23
data1 : 10
data2 : 20
data3 : 30
data4 : 40
after op: 
3;10;20;30;40;

Received: 24;10;20;30;40;

len is 16
data0 : 24
data1 : 10
data2 : 20
data3 : 30
data4 : 40
after op: 
4;10;20;30;40;

Solution

  • 23;10;20;30;40; is 15 characters in length. When you've filled splittedBuffer[4] with 40, you go ahead with the 16:th character to fill ...

    splittedBuffer[dataIndex][bufferIndex] = buffer[i];
    

    ... when dataIndex is 5, which is out of bounds, so the program has undefined behavior.

    A quick fix would be to not continue when dataIndex goes out of bounds:

    for (int i = 0; i < len && dataIndex < 5; i++) {
    //                         ^^^^^^^^^^^^^