c++ - localtime and asctime are unsafe, but the safe functions don't have the same parameters -


this question has answer here:

i'm attempting create timestamps program. on sister's mac (using xcode 4.2) code works fine:

struct tm * timeinfo; time_t rawtime; time (&rawtime); timeinfo = localtime (&rawtime); string timestamp(asctime(timeinfo)); 

however, on pc running visual studio 2012 errors localtime , asctime tell me unsafe functions , recommends using localtime_s , asctime_s. however, function parameters different. i've tried researching functions best can, can't work.

any getting work appreciated.

edit:

struct tm * timeinfo; time_t rawtime; time (&rawtime); timeinfo = localtime_s (&rawtime); string timestamp(asctime_s(timeinfo)); 

the reason functions have different parmaters lack of safety caused have single parameter. in particular, asctime() uses single buffer return time. if like:

char *s1 = asctime((time_t)0);   // 1-jan-1970 00:00:00 or that.  time_t t = time(); char *s2 = asctime(t); cout << "1970: " << s1 << " now:" << s2 << endl; 

then not see 2 different times printed, current time printed twice, both s1 , s2 point same string.

the same applies localtime, returns pointer struct tm - it's same struct tm, if do:

struct tm* t1 = localtime(0); struct tm* t2 = localtime(time());  

you same values in t1 , t2 (with "current" time, not 1970).

so, fix problem, asctime_s , localtime_s have parameter used store data into. asctime_s have second parameter tell function how space there in storage buffer, otherwise, overflow buffer.


Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

c++ - End of file on pipe magic during open -