【问题标题】:Why is sprintf working in one example and not the next?为什么 sprintf 在一个示例中而不是在下一个示例中工作?
【发布时间】:2014-12-29 15:32:40
【问题描述】:

这是我的代码:

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);

我得到的输出是:

cyear is:

cmin is: 7

输出对于 cmonth 或 cday 也不起作用,但 chour 和 cmin 似乎给出了正确的输出。这是怎么回事?

【问题讨论】:

  • 你没有为终止 NUL 字符留出空间。
  • 避免使用sprintf总是使用snprintf

标签: c string integer printf output


【解决方案1】:

如果是 10 月、11 月或 12 月,cmonth 版本将导致缓冲区溢出。 cday 会在当月 10 号或之后缓冲区溢出,chour 会在超过 10 点时溢出,cmin 会在超过 10 分钟时溢出。

因此,您的代码适用于 1970 年 1 月 1 日 00:00,但其他情况则不然!

要解决此问题,请增大缓冲区;并使用snprintf 函数。如果字段不包含您期望的内容,这将保证您不会出现缓冲区溢出。例如:

char chour[6];
snprintf(chour, sizeof chour, "%d", now->tm_hour);

【讨论】:

  • 使用snprintf 保证不会出现缓冲区溢出,但不能保证得到正确的结果。如果缓冲区太短,您无法得到正确的结果。不过,snprintf() 更好。
猜你喜欢
  • 2017-01-18
  • 2016-11-15
  • 2014-01-06
  • 1970-01-01
  • 2022-08-16
  • 1970-01-01
  • 2012-11-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多