【问题标题】:New Warning in gcc 7.4.0 with respect to gcc 5.4.9gcc 7.4.0 中关于 gcc 5.4.9 的新警告
【发布时间】:2019-12-13 14:05:41
【问题描述】:

几天前,我将我的 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);

谢谢

【问题讨论】:

  • 请发布minimal reproducible example,以便其他人重现该警告。警告很清楚 - 您尝试使用 snprintf 499 字节写入 str - 大小为 196 的区域。
  • 你是对的。我编辑原始帖子以提出解决方案。比你
  • 您对snprintf的使用非常无效。您的程序很可能通过溢出为str 分配的允许内存来调用未定义的行为。请创建并发布一个完全可编译、尽可能短的源代码,让其他人重现您遇到的问题。前任。我的电脑上安装了 gcc。我需要做什么才能重现警告?
  • 我发现了这个错误。 str 声明的长度为 200,但 inputData.outDir 的长度声明为 1024。在 2048 年更改 str 的长度在编译期间没有警告。 LP 很好地定义了问题!

标签: gcc gcc-warning


【解决方案1】:

如您所见,HERE GCC 7.1 引入了Wformat-overflow 选项。 这就是为什么现在给你这个警告。

很有可能

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

可能会溢出,因为

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

【讨论】:

    猜你喜欢
    • 2022-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-04
    相关资源
    最近更新 更多