FERBI
FERBI

Reputation: 41

Program is breaking on printf()

After the first printf() the program is breaking and doesn't even reaches the next printf().

void UART_rx(void) {
    char rx_buffer[256];
    int rx_length = read(uart_filestream, (void*) rx_buffer, sizeof(rx_buffer));

    if(rx_length > 0) {
        printf("%s", rx_buffer);
        printf(" ok");
        rx_buffer[12] = '\0';
        printf(" ok");
        char str_id[4];
        char *start;
        start = strchr(rx_buffer, ',');
        start++;
        strcpy(str_id,start);
        int id;
        id = atoi(str_id);
        printf("Liczba typu int: %d, oraz jako ciag znakow: %s\n", id, str_id);
    }
}

Where could the problem be?

Upvotes: 1

Views: 423

Answers (1)

cadaniluk
cadaniluk

Reputation: 15229

The read call probably misses appending a null byte to rx_buffer, which is required by the %s formatter of printf.

Do that by adding it manually1:

printf("%*.*s\n", rx_length, rx_length, rx_buffer);

1 Thanks to @JonathanLeffler!

Note that this requires read to read only sizeof(rx_buffer) - 1 to prevent a buffer overflow if read really reads 256 bytes because then rx_length == 256 and writing to rx_buffer[256] is undefined behavior.


Notes:

  • read returns a ssize_t. Declare rx_length accordingly because int may not be able to hold values, which do fit into ssize_t very well.

Upvotes: 5

Related Questions