为什么sprintf在一个例子而不是下一个例子中工作?

cou*_*sto 2 c string printf integer output

这是我的代码:

time_t tim=time(NULL);                        // acquire time information
struct tm * now=localtime(&tim);

char cyear[3], cmonth[2], cday[2], chour[2], cmin[2];           
int test = 13;
sprintf(cyear, "%d", test);
sprintf(cmonth, "%d", now->tm_mon+1);
sprintf(cday, "%d", now->tm_mday);
sprintf(chour, "%d", now->tm_hour);
sprintf(cmin, "%d", now->tm_min);

printf("cyear is: %s\n",cyear);
printf("cmin is: %s\n",cmin);
Run Code Online (Sandbox Code Playgroud)

我得到的输出是:

cyear is:

cmin is: 7
Run Code Online (Sandbox Code Playgroud)

输出也不适用于cmonth或cday,但chour和cmin似乎给出了正确的输出.这里发生了什么?

M.M*_*M.M 10

cmonth如果是10月,11月或12月,该版本将导致缓冲区溢出.cday如果它是月份的10号或更晚,它将缓冲溢出,如果chour超过10点,cmin它将溢出.如果超过1小时,它将溢出.

所以你的代码在1970年1月1日00:00很好,但不是很多!

要解决此问题,请将缓冲区放大; 并且还使用该snprintf功能.如果字段不包含您的预期,那将保证您不会出现缓冲区溢出.例如:

char chour[6];
snprintf(chour, sizeof chour, "%d", now->tm_hour);
Run Code Online (Sandbox Code Playgroud)