Thanks to visit codestin.com
Credit goes to github.com

Skip to content

<iomanip>: put_time crashes, allocating a huge memory block #924

@ilya314

Description

@ilya314

Environment:
Microsoft Visual Studio Community 2019
Version 16.6.2
Open x64 Native command prompt for VS 2019.
Microsoft (R) C/C++ Optimizing Compiler Version 19.26.28806 for x64

Problem:
std::put_time crashed if all "tm" structure fields are equal -1.
If calling localtime_s with time_t > _MAX__TIME64_T then all "tm" fields filled by -1.
In real application put_time allocate tons of memory and application hang for some time.

#include <iomanip>
#include <sstream>
#include <iostream>
int main(int, char**)
{
    std::time_t t = 335303598060; // t > _MAX__TIME64_T
    tm t_tm;
    auto err = localtime_s(&t_tm, &t); // error, all fileds in t_tm = -1
    std::cout << "errno = " << err << "\n"; // errno = 22
    std::stringstream ss;
    ss << std::put_time(&t_tm, "%Y-%m-%d %H:%M:%S"); // crash, allocate tons on memory
    std::cout << ss.str() << "\n";
    return 0;
}

c:\~repro\cl /EHsc repro.cpp
Microsoft (R) C/C++ Optimizing Compiler Version 19.26.28806 for x64
Copyright (C) Microsoft Corporation.  All rights reserved.

repro.cpp
Microsoft (R) Incremental Linker Version 14.26.28806.0
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:repro.exe
repro.obj

c:\~repro>repro.exe
errno = 22
crash

Expected behavior:
put_time not crashed.

GCC/Clang (checked in Wandbox):
replace

    auto err = localtime_s(&t_tm, &t); // error, all fields in t_tm = -1
    std::cout << "errno = " << err << "\n"; // errno = 22

by

    localtime_r(&t, &t_tm);
    std::cout << "errno = " << errno << "\n";

Result:

errno = 0
12595-05-08 01:21:00

Why MS localtime_s has limitations for time_t maximum value?
As result we have an unsafe code, it is enough to pass a date >3000 year and the application crashes.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingfixedSomething works now, yay!

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions