Weird C ++ Behavior when printing our time on cout

Running the following code:

1 #include <iostream> 2 int main(int argc, char** argv) 3 { 4 time_t t1 = time(0); 5 time_t t(0); 6 std::cout<<"BUG LINE"<<std::endl<< ctime(&t) << ctime(&t1) ; 7 std::cout<<"PRINTS FINE HERE"<<std::endl; 8 std::cout<< ctime(&t); 9 std::cout<< ctime(&t1); 10 return 0; 11 } 

Building: g ++ test1.cpp

 Output: ./a.out BUG LINE Thu Jan 1 01:00:00 1970 Thu Jan 1 01:00:00 1970 PRINTS FINE HERE Thu Jan 1 01:00:00 1970 Wed Jul 10 16:31:48 2013 

Why does the thread get weird in # 6 code?

+4
source share
4 answers

http://www.cplusplus.com/reference/ctime/ctime/

The return value indicates an internal array whose validity or value can be changed by any subsequent call to asctime or ctime .

http://en.cppreference.com/w/cpp/chrono/c/ctime

The string can be split between std::asctime and std::ctime , or it can be overwritten with every call to any of these functions .

In your example, on line 6, ctime(&t1) checked first, then ctime(&t) , which overwrites the line (depending on which rating is not specified first, and compilers often evaluate in the reverse order (often, not always)) .

TL DR: Reading documents can help.

+7
source

The ctime function returns a static string buffer - so the returned string is exactly the same string every time), which means calling it several times on the same line will give undefined behavior (because C and C ++ standards don't tell you in which order they are executed challenges).

The solution is to call two different statements (with ; between) or use the backup access option where you pass the buffer to save the result), for example. ctime_r

+3
source

The problem is that ctime() uses an internal allocated char array, which changes each time ctime() called.

Another problem is that your ctime() can be evaluated in any order in this expression. So what is happening here is that both of them on line 6 are evaluated, but obviously the second is rated second. Then the operators are applied from left to right, but both calls to ctime have already been evaluated, the rest from the left were made later, and now both lines refer to the same thing.

If you put them on different lines, you get the expected behavior.

http://www.cplusplus.com/reference/ctime/ctime/

C-string containing date and time information in a human-readable format.

The return value indicates an internal array whose validity period can be changed by any subsequent call to asctime or ctime.

+1
source

The return value indicates an internal array whose validity period can be changed by any subsequent call to asctime or ctime.

This is exactly what is happening here. One of the two ctime calls on this line is made before the other, but both are made before cout can print them. Since they (possibly) return the same temporary char buffer, you get the same result by the time cout gets print.

0
source

Source: https://habr.com/ru/post/1490750/


All Articles