warning: format not a string literal and no format arguments(警告:格式不是字符串文字,也没有格式参数)
问题描述
我想删除我在这行代码中得到的警告,
文件 *fil;字符 *imp;(...)fprintf(fil,imp);
问题是当我这样做时,它会在文件上准确地写入我想要的内容,但如果我应用 %s 格式,它就不会,像这样
fprintf(fil, "%s", imp);
这个警告是 gcc 告诉你它无法验证 printf 样式函数(printf、fprintf...等)的格式字符串参数的方式.当编译器无法手动查看字符串并确保在运行时一切都按预期进行时,会生成此警告.让我们看几个例子.
案例1.这个字符串可以在编译时验证,编译器会在没有警告的情况下允许它:
<块引用>printf("这个字符串没有格式");
情况 2:对于这种情况,编译器可以检测到您有格式说明符,并会发出不同的警告.在我的机器上它说警告:格式参数太少".
<块引用>//这很可能会使你的机器崩溃printf("%s 不是一个安全的字符串");
案例 3.现在这是您的情况.您正在获取运行时生成的字符串并尝试打印它.您收到的警告是编译器警告您字符串中可能存在格式说明符.比如说bad%sdata".在这种情况下,运行时将尝试访问不存在的参数以匹配 %s.更糟糕的是,这可能是用户试图利用您的程序(导致其读取不安全的数据).
<块引用>char str[200];scanf("%s", str)printf(str)
I want to remove the warning that i get on this line of the code,
FILE *fil;
char *imp;
(...)
fprintf(fil,imp);
the thing is when i do this it writes on the file exactly what i want, but if i apply the format %s it doesn't, like this
fprintf(fil, "%s", imp);
This warning is gcc's way of telling you that it cannot verify the format string argument to the printf style function (printf, fprintf... etc). This warning is generated when the compiler can't manually peek into the string and ensure that everything will go as you intend during runtime. Lets look at a couple of examples.
Case 1. This string can be verified at compile time and the compiler will allow it without warning:
printf("This string has no format");
Case 2: For this case, the compiler can detect that you have a format specifier and will raise a different warning. On my machine it said "warning: too few arguments for format".
// This will most probably crash your machine printf("Not a safe string to %s");
Case 3. Now this is somewhat your case. You are taking a string generated at runtime and trying to print it. The warning you are getting is the compiler warning you that there could be a format specifier in the string. Say for eg "bad%sdata". In this case, the runtime will try to access a non-existent argument to match the %s. Even worse, this could be a user trying to exploit your program (causing it to read data that is not safe to read).
char str[200]; scanf("%s", str) printf(str)
这篇关于警告:格式不是字符串文字,也没有格式参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:警告:格式不是字符串文字,也没有格式参数
基础教程推荐
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01