From d891704c1e041e556267744e99213cc7b80550fd Mon Sep 17 00:00:00 2001 From: Ivan Grokhotkov Date: Fri, 26 Feb 2016 18:31:50 +0300 Subject: [PATCH] Reduce stack usage by Print::printf Print::printf would allocate 1460 bytes on the stack, which in some cases would overflow the stack. Additionally it didn't handle (rare) cases when vsnprintf needed a buffer longer than 1460 bytes. This change makes default stack-allocated buffer 64 bytes long, and checks the result returned by vsnprintf. If a buffer longer than 64 bytes is needed, it is allocated on the heap. --- cores/esp8266/Print.cpp | 27 ++++++++++++++++++++------- 1 file changed, 20 insertions(+), 7 deletions(-) diff --git a/cores/esp8266/Print.cpp b/cores/esp8266/Print.cpp index 06c51e0c1..899bd83d9 100644 --- a/cores/esp8266/Print.cpp +++ b/cores/esp8266/Print.cpp @@ -45,13 +45,26 @@ size_t ICACHE_FLASH_ATTR Print::write(const uint8_t *buffer, size_t size) { } size_t Print::printf(const char *format, ...) { - va_list arg; - va_start(arg, format); - char temp[1460]; - size_t len = ets_vsnprintf(temp, 1460, format, arg); - len = print(temp); - va_end(arg); - return len; + va_list arg; + va_start(arg, format); + char temp[64]; + char* buffer = temp; + size_t len = vsnprintf(temp, sizeof(temp), format, arg); + va_end(arg); + if (len > sizeof(temp) - 1) { + buffer = new char[len + 1]; + if (!buffer) { + return 0; + } + va_start(arg, format); + vsnprintf(buffer, len + 1, format, arg); + va_end(arg); + } + len = write((const uint8_t*) buffer, len); + if (buffer != temp) { + delete[] buffer; + } + return len; } size_t ICACHE_FLASH_ATTR Print::print(const __FlashStringHelper *ifsh) {