Skip to content

Commit e791ec4

Browse files
authored
fix: add null pointer check with std::localtime (#2846)
1 parent 948d09d commit e791ec4

File tree

1 file changed

+8
-1
lines changed

1 file changed

+8
-1
lines changed

include/pybind11/chrono.h

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -161,9 +161,16 @@ template <typename Duration> class type_caster<std::chrono::time_point<std::chro
161161
// > If std::time_t has lower precision, it is implementation-defined whether the value is rounded or truncated.
162162
// (https://en.cppreference.com/w/cpp/chrono/system_clock/to_time_t)
163163
std::time_t tt = system_clock::to_time_t(time_point_cast<system_clock::duration>(src - us));
164+
165+
// std::localtime returns a pointer to a static internal std::tm object on success,
166+
// or null pointer otherwise
167+
std::tm *localtime_ptr = std::localtime(&tt);
168+
if (!localtime_ptr)
169+
throw cast_error("Unable to represent system_clock in local time");
170+
164171
// this function uses static memory so it's best to copy it out asap just in case
165172
// otherwise other code that is using localtime may break this (not just python code)
166-
std::tm localtime = *std::localtime(&tt);
173+
std::tm localtime = *localtime_ptr;
167174

168175
return PyDateTime_FromDateAndTime(localtime.tm_year + 1900,
169176
localtime.tm_mon + 1,

0 commit comments

Comments
 (0)