Localtime c ошибка

Kastlex

0 / 0 / 0

Регистрация: 17.02.2015

Сообщений: 3

1

17.02.2015, 18:00. Показов 13263. Ответов 6

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

студия 13 ругается на функцию

C++
1
2
time_t t = time(0);
    tm *lt = localtime(&t);

и сама ошибка: Ошибка 1 error C4996: ‘localtime’: This function or variable may be unsafe. Consider using localtime_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS.

собственно, рекомендации компилятора я выполнил

C++
1
#define _CRT_SECURE_NO_WARNINGS

но ошибка остается, что делать?



0



7529 / 6394 / 2914

Регистрация: 14.04.2014

Сообщений: 27,855

17.02.2015, 18:04

2

В свойствах проекта поставь «обрабатывать предупреждения как ошибки» — нет.



0



0 / 0 / 0

Регистрация: 17.02.2015

Сообщений: 3

17.02.2015, 18:10

 [ТС]

3

вот так на данный момент, ошибка сохраняется

Миниатюры

'localtime': This function or variable may be unsafe
 



0



7529 / 6394 / 2914

Регистрация: 14.04.2014

Сообщений: 27,855

17.02.2015, 18:14

4

Ошибка или предупреждение?



0



0 / 0 / 0

Регистрация: 17.02.2015

Сообщений: 3

17.02.2015, 18:15

 [ТС]

5

да ошибка, я ведь написал, думал дело в том, что распознает предупреждения как ошибки, но нет, не в этом



0



17414 / 9248 / 2262

Регистрация: 30.01.2014

Сообщений: 16,194

17.02.2015, 19:27

6

Цитата
Сообщение от Kastlex
Посмотреть сообщение

#define _CRT_SECURE_NO_WARNINGS

Это надо писать до подключения всех заголовочных файлов. Иначе не будет работать



2



7529 / 6394 / 2914

Регистрация: 14.04.2014

Сообщений: 27,855

17.02.2015, 19:39

7

С отключенной обработкой предупреждений должно без этой строки работать.



0



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,33625 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,76123 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.7k2 gold badges45 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

45k7 gold badges68 silver badges99 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:dp11dbserver 150927dbserverbayertree.h 264 1 DBServer
    Error 3 error C3861: 'time': identifier not found c:app2t1.h 263 1 DBServer
    Error 4 error C3861: 'localtime': identifier not found c:app2t1.h 264 1 DBServer
    Error 5 error C3861: 'strftime': identifier not found c:app2t1.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:app2t1.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:app2t1.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:app2t1.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 projectstoml-testtoml11tomldatetime.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!

This may or may not be something close to your problem?
Still don’t quite have enough info to be sure what you are doing.
I’d be thinking localtime is not the problem but somewhere in the printfs there are problems . . .

How are you compiling your project?
g++ or gcc?

Can you print a string?? (as opposed to string ptr)
What is a string in your context?

1 problem here:

fprintf(stdout,"# Single electron capture cross sections, %s state-selectiven",res);

If string is typedef a char[] then passing a pointer to it in func args would be better?

Compiling your sample making some assumptions and adding debug (-g3):

gcc -g3 stackoverflow_localtime_crash.c -o socrash

./socrash 

# Single electron capture cross sections, RESSTRING state-selective
# Magic number=20032014, 20 March 2014, 
# Single electron capture cross sections, RESSTRING state-selective
# ^0+ +  -> ^-1+ + ^+
# Method=MCLZ
#  et al. 2014, to be submitted
# ----------------------------------------------------------------------------
# Energy        Cross sections (10^-16 cm^2)
# (eV/u)        LABELSTRING                     �H���u�j 

* lots more JUNK follows
res string itself cannot be passed in on stack and printed *

Segmentation fault (core dumped)

gdb -c core socrash 

Core was generated by `./socrash'.
Program terminated with signal 11, Segmentation fault.
[New process 10298]
#0  0xb770e713 in strlen () from /lib/tls/i686/cmov/libc.so.6
(gdb) bt
#0  0xb770e713 in strlen () from /lib/tls/i686/cmov/libc.so.6
#1  0xb76da6d9 in vfprintf () from /lib/tls/i686/cmov/libc.so.6
#2  0xb76e0b9f in fprintf () from /lib/tls/i686/cmov/libc.so.6
#3  0x08048a42 in prtcsheader (cs=0xbf9e907c, labels=0xbf9e90bc, res=0xbf9e90a8 "RESSTRING") at stackoverflow_localtime_crash.c:66
#4  0x08048b36 in main (argc=Cannot access memory at address 0x0
) at stackoverflow_localtime_crash.c:80
(gdb) list
64      fprintf(stdout,"%-15s","# (eV/u)");
65      for(i=0;labels[i]!=NULL;i++)
66          fprintf(stdout,"t%-14s",labels[i]);
67      fprintf(stdout,"t%-14s","Total");
68  
69  return 0;
(gdb) 

* see line 66 there is also a problem *
might well be the way I have have declared string :-P

66          fprintf(stdout,"t%-14s",labels[i]);

* If you can find a core file yourself then it would be a big help!!! *

If you can’t find core then maybe you could use ltrace.
Run strace to get trace of all system calls a process does.
Run ltrace to get trace of all lib calls a process does.

Try:

strace ls

ltrace ls

On my crashing example:

ltrace ./socrash 1>stdout.log 2>socrash_ltrace.log
less socrash_ltrace.log 

Понравилась статья? Поделить с друзьями:
  • Linux ошибка permission denied
  • Linux как посмотреть ошибки на интерфейсе
  • Linux журнал ошибок системы
  • Linux xampp 403 ошибка
  • Linux ubuntu проверка диска на ошибки