snprintf()使用Warn提示:warning: format not a string literal and no format arguments

部署运行你感兴趣的模型镜像

问题:

使用snprintf()完成字符串的复制操作:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define ARR_SIZE(a)		(sizeof((a))/sizeof((a)[0]))
#define LEN_BUF			5

int main()
{
	char buf[] = "0123456789";
	char buf1[LEN_BUF];
	char buf2[LEN_BUF];
	// char *buf2 = NULL;

	// Source buf greater than dest buf1 causes stack overflow
	// strcpy(buf1, buf);
	// printf("buf1 is: %s\n", buf1);

	// buf2 = calloc(LEN_BUF, sizeof(char));
	memset(buf2, 0, LEN_BUF);
	strncpy(buf2, buf, LEN_BUF);
	printf("buf2 is: %s\n", buf2);
	// free(buf2);

	memset(buf2, 0, LEN_BUF);
	snprintf(buf2, LEN_BUF, buf);
	printf("buf2 is: %s\n", buf2);

	return 0;
}
编译的时候出现错误提示:

david@ubuntu:~/wrk/tmp$ gcc -o strcpy_compare strcpy_compare.c 
strcpy_compare.c: In function ‘main’:
strcpy_compare.c:42:2: warning: format not a string literal and no format arguments [-Wformat-security]
strcpy_compare.c:42:2: warning: format not a string literal and no format arguments [-Wformat-security]
david@ubuntu:~/wrk/tmp$ 

解决办法:

1. 根据提示,应该是format中没有占位符的参数。

snprintf的函数原型是int snprintf(char *restrict buf, size_t n, const char * restrict  format, ...)

给snprintf()加上格式指示符,

snprintf(buf2, LEN_BUF, "%s", buf);
重新编译,警告信息消失:

david@ubuntu:~/wrk/tmp$ gcc -o strcpy_compare strcpy_compare.c 
david@ubuntu:~/wrk/tmp$

问题解决。


您可能感兴趣的与本文相关的镜像

Qwen3-8B

Qwen3-8B

文本生成
Qwen3

Qwen3 是 Qwen 系列中的最新一代大型语言模型,提供了一整套密集型和专家混合(MoE)模型。基于广泛的训练,Qwen3 在推理、指令执行、代理能力和多语言支持方面取得了突破性进展

### 关于解决格式化字符串不是字面量的警告 当编译器发出 `format string is not a string literal` 的警告时,通常是因为传递给格式化函数(如 C/C++ 中的 `printf`, Java 中的 `String.format()` 或 Python 中的相关方法)的参数不是一个常量字符串字面量。这种情况下可能会引发安全漏洞或运行时错误。 #### 解决方案分析 在某些编程语言中,如果格式化字符串动态生成而非硬编码,则可能导致意外行为或被恶意利用。以下是针对不同场景的具体解决方案: 1. **C/C++ 编程中的处理方式** 如果你在使用像 `sprintf` 这样的函数,并且传入了一个非字面量作为格式控制符,可以考虑如下调整: 原始代码可能类似于这样: ```c char *dynamicFormat = getUserInput(); sprintf(buffer, dynamicFormat, value); ``` 改进后的版本应确保格式串始终是一个固定的字面量: ```c const char* safeFormat = "%d"; // 使用固定格式 sprintf(buffer, safeFormat, value); ``` 此外,在现代开发实践中推荐改用更安全的替代品,比如 `snprintf` 来防止缓冲区溢出[^1]。 2. **Java 程序设计下的应对策略** 对于 Java 而言,假如你遇到了类似的告警信息,应该确认是否真的有必要创建新的 String 实例。例如下面的例子展示了如何优化不必要的对象构造操作: ```java String message = new String("Error occurred").concat(errorCode.toString()); System.out.printf(message , additionalInfo ); ``` 更佳实践应该是直接拼接或者采用 StringBuilder 类完成复杂组合任务,同时保持格式说明符为静态定义部分: ```java String formattedMessage = String.format("%s %s", "Error:", errorCode); System.out.println(formattedMessage + " Additional Info:" + additionalInfo); ``` 3. **Python 开发环境里的修正措施** 针对你提到的 Python 场景,原语句存在潜在风险的原因在于 `.format()` 方法的第一个参数并非严格意义上的字符串常量。可以通过修改成以下形式来规避该类问题: ```python print(f'Failed to get col type for {column}, {column.type}') ``` f-string 是一种简洁高效的方式构建内嵌变量表达式的输出内容,而且天然支持语法检查工具识别合法模式[^2]。 另外需要注意的是,无论哪种实现途径都应当遵循最小权限原则——即只暴露必要的数据结构细节给外部调用者;并且定期执行静态代码扫描以发现并修复隐藏缺陷。 ```python def log_failure(column): """Log failure with proper formatting.""" try: # Using f-string ensures compile-time validation of placeholders. print(f'Failed to retrieve column details: Name={column.name} Type={str(column.type)}') except AttributeError as e: handle_exception(e) # Example usage demonstrating robust logging mechanism without triggering warnings. log_failure(some_column_instance) ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值