我应该如何绕过-Wformat-truncation?

问题描述 投票:0回答:1

假设我有一个函数采用int *p,我知道事实只指向0到99之间的值。但是,编译器不知道,所以如果我写:

char buffer[3];
snprintf(buffer, "%02d", *p);

我收到警告(至少在GCC 8.x上) - 它是这样的:

warning: ‘%02d’ directive output may be truncated writing between 2 and 11 bytes into a region of size 2 [-Wformat-truncation=]
   snprintf(buffer, "%02d", *p);

我该如何规避这个警告?

printf compiler-warnings truncation format-string gcc8
1个回答
0
投票

我可以想到三种绕过警告的方法:

  1. 使用GCC编译指示进行局部抑制: #if __GNUC__ >= 8 #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wformat-truncation" #endif snprintf(buffer, "%02d", *p); #if __GNUC__ >= 8 #pragma GCC diagnostic pop #endif
  2. 无用地钳制打印值以使编译器知道范围: char buffer[3]; int clamped_value = min(max(*p,0),99)` and print that instead of `*p`. snprintf(buffer, "%02d", clamped_value);
  3. 人为地将缓冲区大小增加9个字节; char buffer[3+9]; snprintf(buffer, "%02d", p);

但我不喜欢这些。第一种方式不太安全(而且更冗长);第二个浪费时钟周期,第三个浪费堆栈空间。

© www.soinside.com 2019 - 2024. All rights reserved.