mirror of
				https://github.com/esphome/esphome.git
				synced 2025-10-30 22:53:59 +00:00 
			
		
		
		
	time: Make std::string version of strftime() avoid runaway memory allocations (#5348)
This commit is contained in:
		| @@ -49,6 +49,11 @@ std::string ESPTime::strftime(const std::string &format) { | |||||||
|   struct tm c_tm = this->to_c_tm(); |   struct tm c_tm = this->to_c_tm(); | ||||||
|   size_t len = ::strftime(×tr[0], timestr.size(), format.c_str(), &c_tm); |   size_t len = ::strftime(×tr[0], timestr.size(), format.c_str(), &c_tm); | ||||||
|   while (len == 0) { |   while (len == 0) { | ||||||
|  |     if (timestr.size() >= 128) { | ||||||
|  |       // strftime has failed for reasons unrelated to the size of the buffer | ||||||
|  |       // so return a formatting error | ||||||
|  |       return "ERROR"; | ||||||
|  |     } | ||||||
|     timestr.resize(timestr.size() * 2); |     timestr.resize(timestr.size() * 2); | ||||||
|     len = ::strftime(×tr[0], timestr.size(), format.c_str(), &c_tm); |     len = ::strftime(×tr[0], timestr.size(), format.c_str(), &c_tm); | ||||||
|   } |   } | ||||||
|   | |||||||
| @@ -45,6 +45,10 @@ struct ESPTime { | |||||||
|    * |    * | ||||||
|    * @warning This method uses dynamically allocated strings which can cause heap fragmentation with some |    * @warning This method uses dynamically allocated strings which can cause heap fragmentation with some | ||||||
|    * microcontrollers. |    * microcontrollers. | ||||||
|  |    * | ||||||
|  |    * @warning This method can return "ERROR" when the underlying strftime() call fails, e.g. when the | ||||||
|  |    * format string contains unsupported specifiers or when the format string doesn't produce any | ||||||
|  |    * output. | ||||||
|    */ |    */ | ||||||
|   std::string strftime(const std::string &format); |   std::string strftime(const std::string &format); | ||||||
|  |  | ||||||
|   | |||||||
		Reference in New Issue
	
	Block a user