On 05/12/2018 08:29, Matthias Klose wrote:
Control: tags -1 + moreinfo
On 03.12.18 16:06, François Trahay wrote:
Package: gcc-8
Version: 8.2.0-9
Severity: normal
Dear Maintainer,
I have a piece of code in a CMake project that fails to compile when building
in RelWithDebInfo mode.
The problem seems to come from gcc-8 when both -Wall and -O2 options are set:
char* copy_string(const char* str) {
int len = strlen(str)+1;
char* dest = malloc(sizeof(char)*len);
if(dest) {
strncpy(dest, str, len);
}
return dest;
}
gcc reports the following error:
test_strncpy.c:7:3: error: ‘strncpy’ specified bound depends on the length of
the source argument [-Werror=stringop-overflow=]
strncpy(dest, str, len);
^~~~~~~~~~~~~~~~~~~~~~~
test_strncpy.c:5:13: note: length computed here
int len = strlen(str)+1;
^~~~~~~~~~~
cc1: all warnings being treated as errors
In this case, there is no problem in the source code, but -Werror=stringop-
overflow still reports an error.
Gcc only reports an error when -O2 and -Werror=stringop-overflow (which is
enabled by -Wall) are set. Replacing strncpy with memcpy also fixes the
problem.
No, -Werror* is never turned on by -Wall. Please provide a self-contained
example and the command line options used to show the warning/error.
My bad, -Wall prints a warning when used with -O2. If -Werror and -O2
are set, this shows an error.
Here's a self-contained example program.
gcc reports a warning when running:
$ gcc -c test_strncpy.c -Wall -O2
gcc reports an error when running
$ gcc -c test_strncpy.c -Werror -O2
The error/warning to do show when compiled with -O1.
#include <string.h>
#include <stdlib.h>
char* copy_string(const char* str) {
int len = strlen(str);
char* dest = malloc(sizeof(char)*len+1);
strncpy(dest, str, len+1);
return dest;
}