Skip to content

Commit 1c45987

Browse files
committed
Fixes String(float) issue with Stack Smashing
1 parent c5de6b4 commit 1c45987

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

cores/esp32/stdlib_noniso.c

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,32 @@ char* ultoa(unsigned long value, char* result, int base) {
8888
return result;
8989
}
9090

91+
#if 1
92+
// This version is intended to be user proof
93+
// It avoids Stack Smashing issue, even for s = String(-234223.4f, 32) or String(0.0f, 100)
94+
char *dtostrf(double number, signed char width, unsigned char prec, char *s) {
95+
char fmt[34];
96+
// calculates how many characters the integer part of the float will take
97+
sprintf(fmt, "%32.0f", number);
98+
// finds the start of number ignoring the blanks
99+
char *start = fmt;
100+
while (*start == ' ') start++;
101+
unsigned char numSize = strlen(start), maxSize = sizeof(fmt) - 1;
102+
int maxPrec;
103+
104+
if (prec) numSize += 1; // for the '.'
105+
106+
// avoiding Stack smashing protect failure!
107+
if (width > maxSize) width = maxSize;
108+
maxPrec = maxSize - numSize;
109+
prec = maxPrec > 0 ? maxPrec : 0;
110+
111+
sprintf(fmt, "%%%d.%df", width, prec);
112+
sprintf(s, fmt, number);
113+
return s;
114+
}
115+
#else
116+
// orginal code from Arduino ESP8266
91117
char * dtostrf(double number, signed char width, unsigned char prec, char *s) {
92118
bool negative = false;
93119

@@ -160,3 +186,4 @@ char * dtostrf(double number, signed char width, unsigned char prec, char *s) {
160186
*out = 0;
161187
return s;
162188
}
189+
#endif

0 commit comments

Comments
 (0)