Why does gcc not produce a stringop-overflow warning

Viewed 57

Why does following code not produce a warning with gcc?

#include <string.h>

int main() {
  char d[1], s[4] = {0, 1, 2, 3};
  memcpy(d, s, 8);
}

The gcc documentation says:

-Wstringop-overflow

-Wstringop-overflow=type

Warn for calls to string manipulation functions such as memcpy and strcpy that are determined to overflow the destination buffer.

...

Option -Wstringop-overflow=2 is enabled by default.

So I would expect a stringop-overflow warning. But no warnings at all. When trying to run the program it crashes, which makes sense.

gcc -Wall -Wextra -pedantic test.c -o test_app
./test_app
*** stack smashing detected ***: terminated
Aborted

I'm using gcc 11.2, but also tried gcc 9.4. No warning in either case.

1 Answers

When compiled without optimization, produces the warning you expect:

gcc -g -std=c11 -Wall -Wextra -Werror -Wmissing-prototypes -Wstrict-prototypes -fno-common -c str83.c
In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/string.h:194,
                 from str83.c:1:
str83.c: In function ‘main’:
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/secure/_string.h:63:17: error: ‘__builtin___memcpy_chk’ writing 8 bytes into a region of size 1 overflows the destination [-Werror=stringop-overflow=]
   63 |                 __builtin___memcpy_chk (dest, __VA_ARGS__, __darwin_obsz0 (dest))
      |                 ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
str83.c:6:3: note: in expansion of macro ‘memcpy’
    6 |   memcpy(d, s, 8);
      |   ^~~~~~
cc1: all warnings being treated as errors

When compiled with -O3, no warning is produced, presumably because it becomes dead code (no visible side-effects) and the body of the program is reduced to return(0);.

This is a real GCC, not Apple's port of clang masquerading as GCC:

$ gcc --version
gcc (GCC) 11.2.0
Copyright (C) 2021 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

$

It is, however, running on a Mac and therefore using the XCode headers, hence the unwieldy path for <string.h>.

Related