[PATCH] Fix possible segmentation fault in strnstr() on 64-bit systems

Johannes Schindelin johannes.schindelin@gmx.de
Thu Sep 14 13:44:00 GMT 2017

As of f22054c94d (Modify strnstr.c., 2017-08-30), the strnstr()
implementation was replaced by a version that segfaults (at least
sometimes) on 64-bit systems.

The reason: the new implementation uses memmem(), and the prototype of
memmem() is missing because the _GNU_SOURCE constant is not defined
before including <string.h>. As a consequence its return type defaults
to int (and GCC spits out a warning).

On 64-bit systems, the int data type is too small, though, to hold a
full char *, hence the upper 32-bit are cut off and bad things happen
due to a bogus pointer being used to access memory.

Reported as https://github.com/Alexpux/MINGW-packages/issues/2879 in
the MSYS2 project.

Cc: Sichen Zhao <1473996754@qq.com>
Signed-off-by: Johannes Schindelin <johannes.schindelin@gmx.de>
Published-As: https://github.com/dscho/msys2-runtime/releases/tag/fix-strnstr-segfault-v1
Fetch-It-Via: git fetch https://github.com/dscho/msys2-runtime fix-strnstr-segfault-v1
 newlib/libc/string/strnstr.c | 1 +
 1 file changed, 1 insertion(+)

diff --git a/newlib/libc/string/strnstr.c b/newlib/libc/string/strnstr.c
index ce32d0f73e..f6b007813f 100644
--- a/newlib/libc/string/strnstr.c
+++ b/newlib/libc/string/strnstr.c
@@ -31,6 +31,7 @@ QUICKREF
 #undef __STRICT_ANSI__
+#define _GNU_SOURCE
 #include <_ansi.h>
 #include <string.h>

base-commit: 05cfd1aed8b262e82f62acc2de2858d2d2b6679c

More information about the Cygwin-patches mailing list