GCC (and apparently clang as well) specifically requires that memcpy() with an exact overlap does not trigger undefined behaviour (https://gcc.godbolt.org/z/E4rqz7bn6): > Contrary to the standards covering memcpy GCC expects the case of an exact overlap of source and destination to work and not invoke undefined behavior. (from https://gcc.gnu.org/onlinedocs/gcc.pdf) However, it seems valgrind diagnoses these memcpy() calls as invalid, so it may happen that perfectly valid code is diagnosed as invalid due to the compiler's code generation. See also: https://gitlab.freedesktop.org/pipewire/pipewire/-/merge_requests/1799
I'm reluctant to turn off warnings for UB. The compiler can do what it wants. It might be OK with clang and GCC. What about the Intel or AMD compilers? What about portability to MSVS?
I don't suggest turning off the overlap checks altogether. But maybe they could be relaxed to ignore exact overlaps, or there could be an option to not warn about the case where source = destination, or vica versa. > What about the Intel or AMD compilers? What about portability to MSVS? ICC seems to call `_intel_fast_memcpy`, and MSVC seems to call `memcpy`: https://gcc.godbolt.org/z/rbc7P81eo Now admittedly this is a tricky situation because I imagine ideally valgrind should somehow determine if the memcpy() call was generated by the compiler or not, and allow exact overlaps based on that. But I am not sure if that can even be determined (from DWARF?).
Debuginfo won't help with optimized builds. Sanitizers might be able to annotate code like this so that it gets ignored. In Valgrind there are just the two addresses and the size. There's no way to tell that the addresses are for objects of the same size.
Please also see the extensive discussion in bug 148543 and the external links therein.
(In reply to Barnabás Pőcze from comment #0) > GCC (and apparently clang as well) specifically requires that memcpy() with > an exact overlap does not trigger undefined behaviour > (https://gcc.godbolt.org/z/E4rqz7bn6): > > > Contrary to the standards covering memcpy GCC expects the case of an exact overlap of source and destination to work and not invoke undefined behavior. > > (from https://gcc.gnu.org/onlinedocs/gcc.pdf) So that is from the GCC user manual, chapter 2 Language Standards Supported by GCC, 2.1 C Language. I haven't seen it stated so explicitly elsewhere for GCC. Do you happen to have other references or are there any C standard DRs that address this? Asking because a lot of references bugs seem to be unsure whether this really is the case. It would be good if something like the above statement was made for clang also and/or acknowledged by the C or Posix standards.