gcc 7.4.0 中关于 gcc 5.4.9 的新警告

New Warning in gcc 7.4.0 with respect to gcc 5.4.9

几天前,我将 UBUNTU 发行版从 16.04.12 更新到 18.04.01。

此更新导致从 gcc-5.4.0 过渡到 gcc-7-4-0。

在这个系统中,我用 c 开发了一个应用程序,之前使用 -Wall 选项编译, 没有生成警告。

现在我收到以下警告:

src/load_input_file.c: In function ‘load_input_file’:
src/load_input_file.c:60:23: warning: ‘%s’ directive writing up to 499 bytes into a region of size 196 [-Wformat-overflow=]                                                                                           o 
sprintf(str,"cp %s %s",fileName,inputData.outDir);
                   ^~           ~~~~~~~~~
In file included from /usr/include/stdio.h:862:0,
             from hdr/load_input_file.h:3,
             from src/load_input_file.c:1:
/usr/include/x86_64-linux-gnu/bits/stdio2.h:33:10: note: ‘__builtin___sprintf_chk’ output 5 or more bytes (assuming 504) into a destination of size 200                                                                                             
  return __builtin___sprintf_chk (__s, __USE_FORTIFY_LEVEL - 1,
         ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      __bos (__s), __fmt, __va_arg_pack ());
      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

你能帮我理解这个警告是什么以及如何解决它吗? 谢谢

为了解决这个问题,根据 KamilCuk 的建议,我按以下方式修改了代码

sprintf(str,"cp %s %s",fileName,inputData.outDir);

sprintf(str,"cp ");
snprintf(str+strlen(str),strlen(fileName),"%s ",fileName);
snprintf(str+strlen(str),strlen(inputData.outDir),"%s",inputData.outDir);

谢谢

如您所见,HERE GCC 7.1 引入了 Wformat-overflow 选项。 这就是现在向您发出警告的原因。

很有可能

sprintf(str,"cp %s %s",fileName,inputData.outDir);

可以溢出因为

sizeof(fileName)+sizeof(inputData.outDir) > sizeof(str)