...
| Code Block |
|---|
|
#include <time.h>
void func(void) {
struct tm time_tm;
/* Initialize tim *time_tm) */{
char *time = asctime(&time_tm);
/* ... */
} |
Noncompliant Code Example (asctime())
...
| Code Block |
|---|
|
#include <time.h>
int validate_tm(struct tm* time) {
/*
* The range of valid values of the tm_sec member is [0, 60]
* inclusive (to allow for leap seconds).
*/
if (time->tm_sec < 0 || time->tm_sec > 60) return 0;
if (time->tm_min < 0 || time->tm_min >= 60) return 0;
if (time->tm_hour < 0 || time->tm_hour >= 24) return 0;
if (time->tm_mday <= 0 || time->tm_mday > 31) return 0;
if (time->tm_mon < 0 || time->tm_mon >= 12) return 0;
/* Other years are legit but may overflow asctime()'s buffer */
if (time->tm_year < -999 || time->tm_year > 9999) return 0;
if (time->tm_wday < 0 || time->tm_wday >= 7) return 0;
if (time->tm_yday < 0 || time->tm_yday >= 366) return 0;
return 1;
}
void func(void) {
struct tm time_tm;
/* Initialize time_tm) */{
if (!validate_tm(&time_tm)) {
/* Handle error */
}
char *time = asctime(&time_tm);
} |
Note that although this example is safer due to sanitizing the data, it is still noncompliant because asctime() is obsolete. See MSC24-C. Do not use deprecated or obsolescent functions.
...
| Code Block |
|---|
|
#define __STDC_WANT_LIB_EXT1__ 1
#include <time.h>
void func(void) {
struct tm *time_tm;) {
const size_t maxsize = 26;
char buffer[maxsize];
/* Initialize time_tm */
if (asctime_s(buffer, maxsize, &time_tm)) {
/* Handle error */
}
} |
...
| Code Block |
|---|
|
#include <time.h>
void func(void) {
struct tm *time;) {
const size_t maxsize = 26;
char s[maxsize];
/* Current time representation for locale */
const char *format = "%c";
const struct tm *timeptr;
size_t size = strftime(s, maxsize, format, timeptrtime);
} |
This call has the same effects as asctime() but it also ensures that no more than maxsize chars are printed, preventing buffer overflow.
...