Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 655
Thomas Russell Avatar asked Jul 14 '26 09:07

Thomas Russell


1 Answers

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.

like image 121
nullptr Avatar answered Jul 17 '26 18:07

nullptr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!