Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is type-safe in c/c++

Tags:

c++

c

What is type-safe?

What does it mean and why is it important?

In my code error occured This function or variable may be unsafe. What does unsafe mean ?

#include <ctime> 

int compareValues() {

        time_t now = time(0);

        tm* ltm = localtime(&now); //Localtime: This function or variable may be unsafe 

        if ((_year == ltm->tm_year) && (_month == 1 + ltm->tm_mon) && (_day == ltm->tm_mday)) {
            return 1;
        }
    }   

If i put in #define _CRT_SECURE_NO_WARNINGS to my code error is disabled but what does unsafe mean and what does #define _CRT_SECURE_NO_WARNINGS do ?

like image 885
Serhan Erkovan Avatar asked Dec 22 '22 21:12

Serhan Erkovan


1 Answers

This has nothing to do with type safety.

localtime() uses a static storage for its return value; this is not unsafe in general, but it might be a problem when using multithreading.

For this reason, Microsoft wants people to use localtime_s() instead, which uses a user-provided buffer.

However, if you really need to call this function from concurrent threads, I would recommend to use localtime_r() if you want to be portable (Posix-compliant at least), since localtime_s() isn't. The *_r function family generally denotes the re-entrant versions of the functions. Basically, re-entrancy is the feature, that a function can be called, while it is already invoked (running) elsewhere. Re-entrant code is always thread-safe, too.

like image 57
Ctx Avatar answered Dec 26 '22 00:12

Ctx