解决编译时出现的警告:format string is not a string literal (potentially insecure)

   转载自:http://www.cocoachina.com/bbs/read.php?tid=87645



       在Xcode 4.2(iOS 5)之前,我猜大家都和我一样很喜欢下面的调试输出写法:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
     NSString *str = @ "Attention" ;
     
     // first warning
     NSLog (str);
     
     // second warning
     NSLog ([str stringByAppendingFormat:@ ", %@" , @ "Xcode 4.2 do not support this format!" ]);
     
     // third warning
     NSLog ([ NSString stringWithFormat:@ "%@, Xcode 4.2 do not support this format!" , @ "Attention" ]);
     
     // fourth warning
     NSException *exception = [ NSException exceptionWithName:@ "Attention"
                                                      reason:@ "Xcode 4.2 do not support this format!"
                                                    userInfo: nil ];
     
     NSLog (exception);


但是在Xcode 4.2(iOS 5)之后,貌似苹果更新的编译器,出了支持ARC的Apple LLVM compiler 3.0。然后我发现每次编译,以前的这些输出都会产生一个warning(警告,黄色三角形)。
在StackOverflow和iPhone Dev SDK查找相关答案之后,发现在最新版的编译器里面NSLog为了安全,只接受格式化的字符串,因为NSLog底层也是用printf来格式化输出的。
所以上面的写法都会给出警告,可以把上面的写法修改为以下合法模式:


?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
     NSString *str = @ "Attention" ;
     
     // first warning
     NSLog (str);                           // warning
     NSLog (@ "%@" , str);         // solution
     NSLog (str, nil );                    // solution
     
     // second warning
     NSLog ([str stringByAppendingFormat:@ ", %@" , @ "Xcode 4.2 do not support this format!" ]);                         // warning
     NSLog (@ "%@" , [str stringByAppendingFormat:@ ", %@" , @ "Xcode 4.2 do not support this format!" ]);         // solution
     NSLog ([str stringByAppendingFormat:@ ", %@" , @ "Xcode 4.2 do not support this format!" ], nil );                    //solution
     
     // third warning
     NSLog ([ NSString stringWithFormat:@ "%@, Xcode 4.2 do not support this format!" , @ "Attention" ]);             // warning
     NSLog (@ "%@, Xcode 4.2 do not support this format!" , @ "Attention" );                                                                 // solution
     NSLog ([ NSString stringWithFormat:@ "%@, Xcode 4.2 do not support this format!" , @ "Attention" ], nil );       // solution
     
     // fourth warning
     NSException *exception = [ NSException exceptionWithName:@ "Attention"
                                                      reason:@ "Xcode 4.2 do not support this format!"
                                                    userInfo: nil ];
     
     NSLog (exception);                         // warning
     NSLog (@ "%@" , exception);       // solution

### 关于解决格式化字符串不是字面量的警告编译器发出 `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) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值