如何评估gcc格式溢出检查大小72 [英] How to evaluate gcc format-overflow checking size 72

查看:622
本文介绍了如何评估gcc格式溢出检查大小72的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的示例代码(t.c)

My sample code (t.c)

#include <stdio.h>
#include <time.h>
int main() {
        /* 12345678901234567890
         * 2017/09/06 12:28:30  */
        char wtime[19];
        time_t t=time(NULL);
        struct tm *pt = localtime(&t);
        sprintf(wtime, "%04d/%02d/%02d %02d:%02d:%02d", pt->tm_year+1900,
            pt->tm_mon+1, pt->tm_mday, pt->tm_hour, pt->tm_min, pt->tm_sec);
        printf("%s %ld\n", wtime, sizeof(int));
        return 0;
}

gcc -Wall -Wformat=2 -m64 t.c(gcc 7.1.1)的警告消息

Warning message by gcc -Wall -Wformat=2 -m64 t.c (gcc 7.1.1)

t.c:9:47: warning: ‘sprintf’ writing a terminating nul past the end of the destination [-Wformat-overflow=]
  sprintf(wtime, "%04d/%02d/%02d %02d:%02d:%02d", pt->tm_year+1900,
                                               ^
t.c:9:2: note: ‘sprintf’ output between 20 and 72 bytes into a destination of size 19
  sprintf(wtime, "%04d/%02d/%02d %02d:%02d:%02d", pt->tm_year+1900,
  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      pt->tm_mon+1, pt->tm_mday, pt->tm_hour, pt->tm_min, pt->tm_sec);
      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

消息中的数字20是19和一个终止符('\ 0'). 我很纳闷,为什么会有72号呢?如何评估.在此样本中,无需将wtime增大为72.

The number 20 in the message is 19 and one terminator ('\0'). I am wonder, why there is a number 72? How to evaluate it. It is not necessary to increase wtime as size 72 in this sample.

推荐答案

"%d"格式用于int,通常是32位带符号整数类型.这意味着打印时最多可以包含11个字符(10位数字加上负号可能的负号).您有六个含义,最多可以包含66个字符.

The "%d" format is for int, which is usually a 32-bit signed integer type. That means it can have up to 11 characters when printed (10 digits plus a possible minus for negative numbers). You have six of those meaning that's up to 66 character.

然后您还有五个其他字符(每个'/'':'两个,以及一个空格).

Then you have five other characters (two each of '/' and ':', and a space).

加终止符.

那是72.

请记住,"%04d""04"部分表示它将打印四个数字,并在左边填充零,但是如果还有更多数字,它将打印所有这些数字.这不是绝对限制.

And remember that the "04" part of "%04d" means it will print four digits left-padded with zeros, but if there's more digits then it will print all of them. It's not an absolute limit.

因此,至少20个字符,但最多72个字符.

Therefore at least 20 characters, but up to 72.

这篇关于如何评估gcc格式溢出检查大小72的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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