Skip to content

Commit

Permalink
Switch from memcpy to memmove when copying within buffers
Browse files Browse the repository at this point in the history
In the usb_write_bytes and uart_write_bytes routines, a memcpy was previously
used to copy untransmitted bytes to the beginning of the buffer (ud->uart_buffer
and ud->usb_buffer, respectively). Since the source and destination regions of
memory may potentially overlap, the use of memcpy may lead to undefined results.

From the draft C89 standard:

    4.11.2.1 The memcpy function

    Synopsis

             #include <string.h>
             void *memcpy(void *s1, const void *s2, size_t n);

    Description

       The memcpy function copies n characters from the object pointed to
    by s2 into the object pointed to by s1 .  If copying takes place
    between objects that overlap, the behavior is undefined.

    Returns

       The memcpy function returns the value of s1 .

By using memmove rather than memcpy in the usb_write_bytes and uart_write_bytes
routines, the potential for undefined behavior can be avoided.
  • Loading branch information
mgduda committed Jan 29, 2023
1 parent 9d05ed4 commit 67ce071
Showing 1 changed file with 2 additions and 2 deletions.
4 changes: 2 additions & 2 deletions uart-bridge.c
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ void usb_write_bytes(uint8_t itf)

count = tud_cdc_n_write(itf, ud->uart_buffer, ud->uart_pos);
if (count < ud->uart_pos)
memcpy(ud->uart_buffer, &ud->uart_buffer[count],
memmove(ud->uart_buffer, &ud->uart_buffer[count],
ud->uart_pos - count);
ud->uart_pos -= count;

Expand Down Expand Up @@ -245,7 +245,7 @@ void uart_write_bytes(uint8_t itf)
}

if (count < ud->usb_pos)
memcpy(ud->usb_buffer, &ud->usb_buffer[count],
memmove(ud->usb_buffer, &ud->usb_buffer[count],
ud->usb_pos - count);
ud->usb_pos -= count;

Expand Down

0 comments on commit 67ce071

Please sign in to comment.