When -Wstringop-truncation sees a strncpy call where the specified bound is equal to the size of the destination, it looks at the next statement to see if it's dst[i] = '\0';, and if it is, it doesn't warn. But it needs to look at the next nondebug statement, otherwise we can get a false positive with -g, as this testcase shows.
Bootstrapped/regtested on x86_64-linux, ok for trunk? 2018-02-06 Marek Polacek <pola...@redhat.com> PR tree-optimization/84228 * tree-ssa-strlen.c (maybe_diag_stxncpy_trunc): Skip debug statements. * c-c++-common/Wstringop-truncation-3.c: New test. diff --git gcc/testsuite/c-c++-common/Wstringop-truncation-3.c gcc/testsuite/c-c++-common/Wstringop-truncation-3.c index e69de29bb2d..e15e6a42b07 100644 --- gcc/testsuite/c-c++-common/Wstringop-truncation-3.c +++ gcc/testsuite/c-c++-common/Wstringop-truncation-3.c @@ -0,0 +1,20 @@ +/* PR tree-optimization/84228 */ +/* { dg-do compile } */ +/* { dg-options "-Wstringop-truncation -O2 -g" } */ + +char *strncpy (char *, const char *, __SIZE_TYPE__); +struct S +{ + char arr[64]; +}; + +int +foo (struct S *p1, const char *a) +{ + if (a) + goto err; + strncpy (p1->arr, a, sizeof p1->arr); /* { dg-bogus "specified bound" } */ + p1->arr[3] = '\0'; +err: + return 0; +} diff --git gcc/tree-ssa-strlen.c gcc/tree-ssa-strlen.c index c3cf432a921..f0f6535017b 100644 --- gcc/tree-ssa-strlen.c +++ gcc/tree-ssa-strlen.c @@ -1849,7 +1849,7 @@ maybe_diag_stxncpy_trunc (gimple_stmt_iterator gsi, tree src, tree cnt) /* Look for dst[i] = '\0'; after the stxncpy() call and if found avoid the truncation warning. */ - gsi_next (&gsi); + gsi_next_nondebug (&gsi); gimple *next_stmt = gsi_stmt (gsi); if (!gsi_end_p (gsi) && is_gimple_assign (next_stmt)) Marek