a new warning could detect problems earlier than "-fsanitize=object-size". The following code is wrong, should be detected by "-fsanitize=object-size", but it could be detected already at compile-time, especially for memset/memcpy/memcmp . char a[8], b[16]; memcpy(a,b,sizeof(b)); // write out of bounds, a[8..15] does not exist Thanks for reading
You might get the warning with -D_FORTIFY_SOURCE=1 but I have not tried it myself.
-D_FORTIFY_SOURCE=1 or -D_FORTIFY_SOURCE=2 handle this well: warning: call to __builtin___memcpy_chk will always overflow destination buffer
I agree there's an opportunity to diagnose a subset of buffer overflows and other simple out-of-bounds accesses during translation and without optimization. For example, in the slightly less trivial example below, the call to memcpy() clearly overwrites the destination buffer and could be diagnosed (it is neither diagnosed nor prevented with _FORTIFY_SOURCE): void f (unsigned N) { int a [N]; read (0, a, sizeof a); char b [N]; memcpy (b, a, sizeof a); write (1, b, sizeof a); } Rather than in the sanitizer which typically involves run-time instrumentation and has a considerable performance overhead, I think it would be better done in GCC under the -Warray-bounds option (without requiring optimization for the simple cases). -Warray-bounds doesn't warn about code like the above even when the value of N is a known (including a constant expression). _FORTIFY_SOURCE could also be enhanced to detect this problem. Since this latter part is something I'm supposed to be looking into I'll confirm this request, adjust the Summary, and for lack of a better alternative set the Component to tree-optimization.
The -Wstringop-overflow option has been added to warn on many of these types of problems. Unfortunately, it doesn't handle this particular case because GCC transforms the memcpy call to assignment before the warning gets a chance to detect it. It's also defeated by the -Wno-system-headers option on systems that define memcpy et al. as macros in <string.h>. Since these limitations are being tracked in other bugs (the former in bug 79220 and the latter in bug 79214) I'll go ahead and resolve this enhancement request as fixed. Please open new bugs with any additional requests or for new problems in -Wstringop-overflow.