【发布时间】:2011-05-05 03:35:43
【问题描述】:
我偶尔在 sprintf_s 执行以下代码时发生崩溃。这段代码工作了很多年,没有任何问题。当我在下面的语句中给出 strcat_s 和 sprintf_s 的大小时,没有出现崩溃。这可能是什么原因?
strcat_s(sztmpCurrDate,100,sztmpCurrTime); sprintf_s(sztmpCurrDate,100,"%s:%0.3d",sztmpCurrDate,curTime.wMilliseconds););
char sztmpCurrDate[100] = "";
char sztmpCurrTime[100] = "";
SYSTEMTIME curTime;
GetLocalTime(&curTime);
GetLocalTime(&curTime);
GetDateFormat(LOCALE_USER_DEFAULT,
DATE_SHORTDATE,
&curTime,
NULL,
sztmpCurrDate,
100);
GetTimeFormat(LOCALE_USER_DEFAULT,
TIME_FORCE24HOURFORMAT,
&curTime,
"HH':'mm':'ss",
sztmpCurrTime,
100);
strcat_s(sztmpCurrDate," ");
strcat_s(sztmpCurrDate,sztmpCurrTime);
sprintf_s(sztmpCurrDate,"%s:%0.3d",sztmpCurrDate,curTime.wMilliseconds);
【问题讨论】:
-
您是否使用 ..._s 版本,因为您的代码没有像我预期的那样传递缓冲区的大小。
-
有一个模板化版本的 sprintf_s 可以使用固定大小的缓冲区。
-
sprintf_s 有 _s 后缀,这意味着它不安全... ;)