Localtime c ошибка

I got a problem on visual studio.
I try to use the localtime function from «time.h».

Visual studio tells me it’s an unsafe function. However, I have tu use this one for my school exercice. I saw that you can disable this unsafe error by going in the project properties, build tab, and check «enable unsafe code».

Nevertheless, I don’t have a build tab, as you can see there :
http://puu.sh/4NkYC.png

I’m using windows 7 and visual studio 2012 Ultimate. It looks like the «build tab» and «enable unsafe code» has vanished :/
Maybe you know how to fix that ?

thank’s a lot :)

asked Oct 11, 2013 at 15:25

QuentinRM's user avatar

2

You can switch off the warning using the following directive:

#pragma warning(disable : 4996) //_CRT_SECURE_NO_WARNINGS

answered Apr 9, 2016 at 19:28

AlexMelw's user avatar

AlexMelwAlexMelw

2,42627 silver badges35 bronze badges

0

localtime is marked unsafe by the MS-Compiler because it returns a pointer to a statically allocated struct tm. This is obviously a bad idea.
Therefore, localtime_s was invented by Microsoft, which takes a pointer to a struct tm allocated by you
struct tm timeinfo;
localtime_s(&timeinfo, &rawtime);


Use this (and have your program be Microsoft specific) or switch off the warning by defining _CRT_SECURE_NO_WARNINGS.

answered Oct 11, 2013 at 15:49

Henno's user avatar

HennoHenno

3971 silver badge7 bronze badges

Visual Studio (VS) compiler gives this error. It’s simple to get rid of this problem.

  1. Go to your VS context menu Project>Properties.
  2. Click Configuration>Properties>C/C++>Preprocessor.
  3. Edit Preprocessor Definitions and add _CRT_SECURE_NO_WARNINGS last empty line.

This compile warning will be gone.

answered Sep 12, 2015 at 9:59

Umut D.'s user avatar

Umut D.Umut D.

1,74623 silver badges24 bronze badges

unsafe is part of C# not C++. For example these docs clearly say

/unsafe (C# Compiler Options)

at the top

In C++, visual studio will complain about functions it regards as unsecure and suggest you #define _CRT_SECURE_NO_WARNINGS if you don’t want lots of warnings, for example

localtime might give you the following:

warning C4996: ‘localtime’: This function or variable may be unsafe.
Consider using localtime_s instead. To disable deprecation, use
_CRT_SECURE_NO_WARNINGS. See online help for details.

answered Oct 11, 2013 at 15:32

doctorlove's user avatar

doctorlovedoctorlove

18.9k2 gold badges46 silver badges62 bronze badges

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h> 
#include <stdlib.h> 
#include <time.h> 
char counter_str[10];

int main()
{ 
  time_t my_time = time(NULL)// declaring argument of time();
  sprintf(counter_str,ctime(&my_time));//fetch current time
  printf(counter_str);

}

answered Dec 13, 2019 at 23:02

Sreejith Sathyan's user avatar

2

The portable, «safe» version of localtime is localtime_r. Like Microsoft’s localtime_s mentioned in Henno’s answer, localtime_r takes an additional argument which is a pointer to the struct tm to fill in, rather than using a shared, statically-allocated one as localtime does.
Example:

time_t t = time(NULL);
struct tm tmbuf;
localtime_r(&t, &tmbuf);

answered Oct 26, 2022 at 16:23

Steve Summit's user avatar

Steve SummitSteve Summit

45.6k7 gold badges70 silver badges103 bronze badges

I got a problem on visual studio.
I try to use the localtime function from «time.h».

Visual studio tells me it’s an unsafe function. However, I have tu use this one for my school exercice. I saw that you can disable this unsafe error by going in the project properties, build tab, and check «enable unsafe code».

Nevertheless, I don’t have a build tab, as you can see there :
http://puu.sh/4NkYC.png

I’m using windows 7 and visual studio 2012 Ultimate. It looks like the «build tab» and «enable unsafe code» has vanished :/
Maybe you know how to fix that ?

thank’s a lot :)

asked Oct 11, 2013 at 15:25

QuentinRM's user avatar

2

You can switch off the warning using the following directive:

#pragma warning(disable : 4996) //_CRT_SECURE_NO_WARNINGS

answered Apr 9, 2016 at 19:28

AlexMelw's user avatar

AlexMelwAlexMelw

2,42627 silver badges35 bronze badges

0

localtime is marked unsafe by the MS-Compiler because it returns a pointer to a statically allocated struct tm. This is obviously a bad idea.
Therefore, localtime_s was invented by Microsoft, which takes a pointer to a struct tm allocated by you
struct tm timeinfo;
localtime_s(&timeinfo, &rawtime);


Use this (and have your program be Microsoft specific) or switch off the warning by defining _CRT_SECURE_NO_WARNINGS.

answered Oct 11, 2013 at 15:49

Henno's user avatar

HennoHenno

3971 silver badge7 bronze badges

Visual Studio (VS) compiler gives this error. It’s simple to get rid of this problem.

  1. Go to your VS context menu Project>Properties.
  2. Click Configuration>Properties>C/C++>Preprocessor.
  3. Edit Preprocessor Definitions and add _CRT_SECURE_NO_WARNINGS last empty line.

This compile warning will be gone.

answered Sep 12, 2015 at 9:59

Umut D.'s user avatar

Umut D.Umut D.

1,74623 silver badges24 bronze badges

unsafe is part of C# not C++. For example these docs clearly say

/unsafe (C# Compiler Options)

at the top

In C++, visual studio will complain about functions it regards as unsecure and suggest you #define _CRT_SECURE_NO_WARNINGS if you don’t want lots of warnings, for example

localtime might give you the following:

warning C4996: ‘localtime’: This function or variable may be unsafe.
Consider using localtime_s instead. To disable deprecation, use
_CRT_SECURE_NO_WARNINGS. See online help for details.

answered Oct 11, 2013 at 15:32

doctorlove's user avatar

doctorlovedoctorlove

18.9k2 gold badges46 silver badges62 bronze badges

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h> 
#include <stdlib.h> 
#include <time.h> 
char counter_str[10];

int main()
{ 
  time_t my_time = time(NULL)// declaring argument of time();
  sprintf(counter_str,ctime(&my_time));//fetch current time
  printf(counter_str);

}

answered Dec 13, 2019 at 23:02

Sreejith Sathyan's user avatar

2

The portable, «safe» version of localtime is localtime_r. Like Microsoft’s localtime_s mentioned in Henno’s answer, localtime_r takes an additional argument which is a pointer to the struct tm to fill in, rather than using a shared, statically-allocated one as localtime does.
Example:

time_t t = time(NULL);
struct tm tmbuf;
localtime_r(&t, &tmbuf);

answered Oct 26, 2022 at 16:23

Steve Summit's user avatar

Steve SummitSteve Summit

45.6k7 gold badges70 silver badges103 bronze badges

  • Remove From My Forums
  • Question

  • Hi,
    how to resolve these

    Error 2 error C4996: 'localtime': This function or variable may be unsafe. Consider using localtime_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. c:\dp11\dbserver 150927\dbserver\bayertree.h 264 1 DBServer
    Error 3 error C3861: 'time': identifier not found c:\app2\t1.h 263 1 DBServer
    Error 4 error C3861: 'localtime': identifier not found c:\app2\t1.h 264 1 DBServer
    Error 5 error C3861: 'strftime': identifier not found c:\app2\t1.h 266 1 DBServer

    due to these

    258  t00.open("c:\\00.txt");
    259  time_t rawtime;
    260  struct tm * timeinfo;
    261  char buffer[80];
    262
      time(&rawtime);
      timeinfo = localtime(&rawtime);
    
    
      strftime(buffer, 80, "%d-%m-%Y %I:%M:%S", timeinfo);
      std::string str(buffer);
    
    
      //
      t00 << str;
    
    
      t00.close();


    Many Thanks & Best Regards, Hua Min

Answers

  • how to resolve these
    Error 2
    error C2664: ‘errno_t localtime_s(tm *,const time_t *)’ : cannot convert argument 1 from ‘tm **’ to ‘tm *’
    c:\app2\t1.h 266
    1 DBServer

    err = localtime_s(&timeinfo, &rawtime);

    The message is clear enough: you’re passing a pointer to a pointer when you should be

    passing just a pointer. Look at the examples in the documentation, and don’t just guess
    at what to code.

    Change:

    struct tm * timeinfo;

    to:

    struct tm timeinfo;

    — Wayne

    • Proposed as answer by

      Monday, November 30, 2015 8:11 AM

    • Marked as answer by
      May Wang — MSFT
      Monday, December 7, 2015 9:49 AM

  • I include both time.h and ctime, but I still get these

    Error	2	error C4996: 'localtime': This function or variable may be unsafe. Consider using localtime_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.	c:\app2\t1.h	266	1	DBServer
    Error	3	error C4996: 'localtime': This function or variable may be unsafe. Consider using localtime_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.	c:\app2\t1.h	266	1	DBServer

    If you don’t want to change functions, look up the C4996 message to learn several different ways to suppress it.

    • Proposed as answer by
      May Wang — MSFT
      Monday, November 30, 2015 8:11 AM
    • Marked as answer by
      May Wang — MSFT
      Monday, December 7, 2015 9:49 AM

@patrikhuber

Hi!

Thanks for this great project, it seems like one of the best header-only modern C++ TOML APIs out there! :-)

I’ve got a compilation error when compiling with VS2017, 15.3.0 Preview:

Severity Code Description Project File Line Suppression State
Error C4996 ‘localtime’: This function or variable may be unsafe. Consider using localtime_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. toml-test projects\toml-test\toml11\toml\datetime.hpp 71

The line in question is std::tm* t_ = std::localtime(&t);.

I think this is probably a longstanding warning that got turned into an error in VS2017.
I tried to fix it but haven’t gotten too far yet: Changing it into std::localtime_s doesn’t work as that function doesn’t exist — there exists one called localtime_s from C11 (without the std:: prefix) but it does not take 1 argument.

@ToruNiina

Hi, thank you for the issue.
As you pointed out, localtime is not thread-safe.

I’m not sure it is the best way to use C11 function because this is a C++11 project and C++11 is not compatible with C11. But it is also true that the problem should be fixed.

I think you can avoid the problem by doing this.

std::tm t_;
localtime_s(std::addressof(t), std::addressof(t_));

A similar problem might occur with gmtime and can be fixed in the same way (with gmtime_s, also since C11).

I will add a workaround for this problem, but it possibly take some time.

ToruNiina

added a commit
that referenced
this issue

Aug 11, 2017

@ToruNiina

@patrikhuber

Hi!

The error seems a bit weird actually — I got it reproducibly but now it’s gone for some reason. I first thought it depends on some VS project settings, whether this results in an error or not, so if you’re in a CMake generated VS project file (with default settings), it behaves differently than in a VS generated project. But now for some reason it currently works in both. (And I didn’t pull your fix yet). I am not sure at this point.

Agreed that a C11 function might also not be the best idea if it is not available on at least all the major recent compilers, but even then a standard C++ function would be better.

@rathaROG

Hi @patrikhuber! How do you fix this?

Edit: My temporary solution is add _CRT_SECURE_NO_WARNINGS to Preprocessor Definitions.

@patrikhuber

Hi @rathaROG, the error disappeared for me — not sure why. But ToruNiina also committed somethhing that should fix it, see above.

@patrikhuber

I think we can close this, I didn’t have any issues with toml11 in VS2017 since. Thanks!

The localtime() function in C is used to convert the time given in seconds since the Epoch into a broken-down time structure. It is commonly used in C programs for a variety of tasks related to time handling. However, there are several common mistakes that programmers make when using localtime(), which can lead to inaccurate or unexpected results. In this article, we will discuss some of these common mistakes and how to fix them.

Mistake #1: Not checking for errors

One common mistake that programmers make when using localtime() is not checking for errors in the function. The localtime() function can return a null pointer if an error occurs during the conversion process, such as if the given time value is outside the range of representable time values. If the programmer does not check for this null pointer, the program may end up accessing invalid memory, leading to undefined behavior.

To fix this mistake, the programmer should always check for errors when using localtime(). One way to do this is to check the return value of the function against a null pointer, as shown below:

time_t t = /* some time value */;

struct tm* broken_down_time = localtime(&t);

if (broken_down_time == NULL)
{
    /* handle error */
}

Mistake #2: Not initializing the time structure

Another common mistake that programmers make is not initializing the tm structure before calling localtime(). The localtime() function populates the tm structure with various fields representing the broken-down time values, such as the year, month, day, hour, minute, and second. If the programmer does not initialize these fields beforehand, their values may be arbitrary, leading to unexpected results.

To fix this mistake, the programmer should initialize the tm structure before calling localtime(). One way to do this is to use the memset() function to set all fields to zero, as shown below:

time_t t = /* some time value */;

struct tm broken_down_time;
memset(&broken_down_time, 0, sizeof(struct tm));

localtime_r(&t, &broken_down_time);

Note that in this case, we are using the localtime_r() function instead of localtime(). The _r suffix denotes a reentrant version of the function that uses a thread-safe internal buffer, rather than a static buffer as in the non-reentrant version. This is generally considered a safer option in a multithreaded environment.

Mistake #3: Not accounting for daylight saving time

A more subtle mistake that programmers can make is not accounting for daylight saving time when using localtime(). Daylight saving time (DST) is a system whereby the clock is adjusted by one hour in order to extend the amount of daylight in the evenings during the summer months. However, this means that the local time can jump forward or backward by one hour at certain times during the year, depending on the location and time zone.

The localtime() function takes into account the DST configuration of the system, and adjusts the broken-down time values accordingly. However, this also means that the function may return different values for the same input time value, depending on whether DST is in effect or not. If the programmer does not account for this, their program may produce incorrect results.

To fix this mistake, the programmer should make sure to account for DST when using localtime(). One way to do this is to use the mktime() function to convert the broken-down time structure back into a time value, and compare it against the original input time value. If the two values differ by exactly one hour, this indicates a DST transition, and the programmer can adjust the broken-down time structure accordingly.

time_t t = /* some time value */;

struct tm* broken_down_time = localtime(&t);

time_t t2 = mktime(broken_down_time);

if (t2 == -1)
{
    /* handle error */
}

if (t2 == t + 3600 || t2 == t - 3600)
{
    /* DST transition, adjust hour field */
    if (t2 > t)
    {
        /* DST forward, add one hour */
        broken_down_time->tm_hour++;
    }
    else
    {
        /* DST backward, subtract one hour */
        broken_down_time->tm_hour--;
    }

    /* re-normalize broken-down time */
    mktime(broken_down_time);
}

Conclusion

The localtime() function is a powerful tool for handling time values in C programs. However, as we have seen, there are several common mistakes that programmers can make when using this function. By following the guidelines presented in this article, programmers can avoid these mistakes and ensure that their programs correctly handle all possible time values.

Понравилась статья? Поделить с друзьями:
  • Loading ibss component ошибка
  • Libreoffice если ошибка
  • Loading error failed to load audio bgm ошибка
  • Libreoffice calc ошибка 507
  • Loch ошибка на стиральной машине хаер