简体   繁体   中英

Invalid null pointer error when converting std::chrono::system_clock::time_point::min() to string

I am following an example in Nicolai M. Josuttis' "The C++ Standard Library (Second Edition)", page 152-153, which details an example to print the epoch, current time, minimum and maximum times of the std::chrono::system_clock introduced in C++11.

I am using Microsoft Visual Studio 2012, and get an assertion triggered in <xstring> , due to an invalid null pointer. This occurs on the line std::string ts = std::ctime( &t ) in the code below after setting tp = std::chrono::system_clock::time_point::min();

#include <chrono>
#include <ctime>
#include <string>
#include <iostream>

std::string asString( const std::chrono::system_clock::time_point& tp )
{
    std::time_t t = std::chrono::system_clock::to_time_t( tp );
    std::string ts = std::ctime( &t );
    ts.resize( ts.size()-1 );
    return ts;
}

int main()
{
    std::chrono::system_clock::time_point tp;
    std::cout << "epoch: " << asString(tp) << std::endl;

    tp = std::chrono::system_clock::now();
    std::cout << "now: " << asString(tp) << std::endl;

    tp = std::chrono::system_clock::time_point::min();
    std::cout << "min: " << asString(tp) << std::endl;

    tp = std::chrono::system_clock::time_point::max();
    std::cout << "max: " << asString(tp) << std::endl;

    return 0;
}

Is this due to an implementation error by Dinkumware in the <chrono> library, or just a typo/mistake in the book? I have gone over the code given in the book again and again to see if I have copied it out incorrectly, but this does not appear to be the case. I'd be very grateful for any insights given.

It looks like std::ctime returns NULL, which indicates an incorrect t value. Probably because the call to asString uses a value of time_point that cannot be represented in time_t type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM