Skip to content

Commit d891704

Browse files
committed
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.
1 parent f28c5be commit d891704

File tree

1 file changed

+20
-7
lines changed

1 file changed

+20
-7
lines changed

cores/esp8266/Print.cpp

+20-7
Original file line numberDiff line numberDiff line change
@@ -45,13 +45,26 @@ size_t ICACHE_FLASH_ATTR Print::write(const uint8_t *buffer, size_t size) {
4545
}
4646

4747
size_t Print::printf(const char *format, ...) {
48-
va_list arg;
49-
va_start(arg, format);
50-
char temp[1460];
51-
size_t len = ets_vsnprintf(temp, 1460, format, arg);
52-
len = print(temp);
53-
va_end(arg);
54-
return len;
48+
va_list arg;
49+
va_start(arg, format);
50+
char temp[64];
51+
char* buffer = temp;
52+
size_t len = vsnprintf(temp, sizeof(temp), format, arg);
53+
va_end(arg);
54+
if (len > sizeof(temp) - 1) {
55+
buffer = new char[len + 1];
56+
if (!buffer) {
57+
return 0;
58+
}
59+
va_start(arg, format);
60+
vsnprintf(buffer, len + 1, format, arg);
61+
va_end(arg);
62+
}
63+
len = write((const uint8_t*) buffer, len);
64+
if (buffer != temp) {
65+
delete[] buffer;
66+
}
67+
return len;
5568
}
5669

5770
size_t ICACHE_FLASH_ATTR Print::print(const __FlashStringHelper *ifsh) {

0 commit comments

Comments
 (0)