0
votes

I have level 4 warning in my C++ project I want to solve it the warning is

Warning 1 warning C4996: 'gmtime': This function or variable may be unsafe. Consider using gmtime_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.

Warning 2 warning C4996: 'asctime': This function or variable may be unsafe. Consider using asctime_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.

code C++

time_t ltime;
time(&ltime);
tm* gmt = gmtime(&ltime);

char* asctime_remove_nl = asctime(gmt);
1
Why don't you do as recommended and use gmtime_s and asctime_s ?Daan Timmer
@DaanTimmer I don't now how to use it ?user474901
Why don’t you simply do what the warning tells you to disable it? That said, the warning is right: do not use these functions, they are deprecated for a reason. The POSIX standard defines replacement functions.Konrad Rudolph
Uh, if you want to just silence the warning the message says how to do that, if you want to know how to use those functions good way to start would be typing their names into a search engine. Also see MSDN page about warning C4996.user2802841

1 Answers

1
votes

Below functions return pointers to static objects that may be overwritten by other subsequent calls(K&R Book). Hence they are not considered to be safe and due to this VS compiler would give the warning/error. It can be removed by adding the MACRO in the project(.proj file)(CRT_SECURE_NO_WARNINGS).

gmtime()
asctime()

However, we can write the small utility functions which would make the copy of these static strings.

// This would return the copy of time/date in std::string object to caller
std::string get_gmtime_asctime() {
 time_t ltime;
 time(&ltime);
 struct tm* gt = ::gmtime(&ltime);
 char* tmp = ::asctime(gt);
 std::string output(tmp);
 return output;
}

int main() {
    std::string out = get_gmtime_asctime();
    std::cout<<out<<std::endl;

}