diff --git a/gcc/fold-const.c b/gcc/fold-const.c
index 1694ba4554bf2f8c6f9b118f5e353040ce8d96cf..3a0f39a85b8c99d33cee9253f536c6f05898c2f2 100644
--- a/gcc/fold-const.c
+++ b/gcc/fold-const.c
@@ -8280,9 +8280,9 @@ native_encode_initializer (tree init, unsigned char *ptr, int len,
 		    return 0;
 		  if (pos + fieldsize > total_bytes)
 		    {
-		      if (ptr != NULL && total_bytes - o < len)
-			memset (ptr + (total_bytes - o),
-				'\0', MIN (pos + fieldsize - o, len));
+		      if (ptr != NULL && total_bytes < len)
+			memset (ptr + total_bytes, '\0',
+				MIN (pos + fieldsize, len) - total_bytes);
 		      total_bytes = pos + fieldsize;
 		    }
 		}
diff --git a/gcc/testsuite/gcc.c-torture/compile/pr98407.c b/gcc/testsuite/gcc.c-torture/compile/pr98407.c
new file mode 100644
index 0000000000000000000000000000000000000000..29eb0803944afd2e4422c55d9400379d092eb2c5
--- /dev/null
+++ b/gcc/testsuite/gcc.c-torture/compile/pr98407.c
@@ -0,0 +1,10 @@
+/* PR tree-optimization/98407 */
+
+struct S { int a; int b[]; };
+const struct S c = { 0, { 0 } }, d = { 0, { 0 } };
+
+int
+foo (void)
+{
+  return __builtin_memcmp (&c, &d, sizeof d);
+}