我的示例代码(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
(海湾合作委员会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 和 1 个终止符('\0')。
我很好奇,为什么是72这个数字?怎么评价呢。在此示例中,无需将 wtime 增加为大小 72。