fprintf,错误:格式不是字符串文字且没有格式参数 [-Werror=format-security [英] fprintf, error: format not a string literal and no format arguments [-Werror=format-security

查看:63
本文介绍了fprintf,错误:格式不是字符串文字且没有格式参数 [-Werror=format-security的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试在 Ubuntu 上编译 fprintf(stderr,Usage) 时出现此错误:

when I try to compile fprintf(stderr,Usage) on Ubuntu I got this error:

 error: format not a string literal and no format arguments [-Werror=format-security

但是当我在其他编译成功的 Linux 发行版(RedHat、Fedora、SUSE)上编译它时.

but when I compiled that on other linux distributions (RedHat, Fedora, SUSE) that is compiled successfully.

有人有想法吗?

推荐答案

你应该使用 fputs(Usage, stderr);

如果您不进行格式化,则无需使用 fprintf.如果要使用 fprintf,请使用 fprintf(stderr, "%s", Usage);

There is no need to use fprintf if you arn't doing formatting. If you want to use fprintf, use fprintf(stderr, "%s", Usage);

Ubuntu 上的 默认编译器标志 包括 -Wformat -Wformat-security 这就是导致此错误的原因.

The default compiler flags on Ubuntu includes -Wformat -Wformat-security which is what gives this error.

该标志用于防止引入与安全相关的错误,想象一下如果你以某种方式这样做,就会发生:

That flag is used as a precaution against introducing security related bugs, imagine what would happen if you somehow did this:

char *Usage = "Usage %s, [options] ... ";
...
fprintf(stderr, Usage);

这将与fprintf(stderr, "Usage %s, [options] ... ]"); 这是错误的.

现在 Usage 字符串包含格式说明符 %s,但您没有将该参数提供给 fprintf,从而导致未定义的行为,可能会导致您的程序崩溃或被利用.如果您传递给 fprintf 的字符串来自用户输入,则这更相关.

Now the Usage string includes a format specifier, %s, but you do not provide that argument to fprintf, resulting in undefined behavior, possibly crashing your program or allowing it to be exploited. This is more relevant if the string you pass to fprintf comes from user input.

但是如果你做 fprintf(stderr,"%s", "Usage %s, [options] ... ]"); 就没有这个问题了.2. %s 不会被解释为格式说明符.gcc 可以对此发出警告,默认的 Ubuntu 编译器标志使其成为编译器错误.

But if you do fprintf(stderr,"%s", "Usage %s, [options] ... ]"); There is no such problem. The 2. %s will not be interpreted as a format specifer. gcc can warn about this, and the default Ubuntu compiler flags makes it a compiler error.

这篇关于fprintf,错误:格式不是字符串文字且没有格式参数 [-Werror=format-security的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆