Skip to content

Commit c6ab73b

Browse files
committed
Fixes String(float) issue with Stack Smashing
1 parent f3c7b49 commit c6ab73b

File tree

2 files changed

+6
-43
lines changed

2 files changed

+6
-43
lines changed

cores/esp32/WString.cpp

+6-5
Original file line numberDiff line numberDiff line change
@@ -114,14 +114,15 @@ String::String(unsigned long value, unsigned char base) {
114114

115115
String::String(float value, unsigned char decimalPlaces) {
116116
init();
117-
char buf[64];
118-
*this = dtostrf(value, sizeof(buf) - 1, decimalPlaces, buf);
119-
}
117+
char *buf = (char*)malloc(decimalPlaces + 42);
118+
*this = dtostrf(value, (decimalPlaces + 2), decimalPlaces, buf);
119+
free(buf);}
120120

121121
String::String(double value, unsigned char decimalPlaces) {
122122
init();
123-
char buf[64];
124-
*this = dtostrf(value, sizeof(buf) - 1, decimalPlaces, buf);
123+
char *buf = (char*)malloc(decimalPlaces + 312);
124+
*this = dtostrf(value, (decimalPlaces + 2), decimalPlaces, buf);
125+
free(buf);
125126
}
126127

127128
String::~String() {

cores/esp32/stdlib_noniso.c

-38
Original file line numberDiff line numberDiff line change
@@ -88,43 +88,6 @@ 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[20]; // just for the formating in sprintf()
96-
uint8_t numSize = 0;
97-
int maxPrec;
98-
99-
if (isnan(number)) {
100-
strcpy(s, "nan");
101-
return s;
102-
}
103-
if (isinf(number)) {
104-
strcpy(s, "inf");
105-
return s;
106-
}
107-
108-
// calculates how many characters the integer part of the float will take
109-
if (number < 0) { // number is negative
110-
numSize = 1; // for the '-' simbol
111-
}
112-
double n = fabs(number);
113-
do {
114-
numSize++;
115-
n = n / 10;
116-
} while (n > 1);
117-
if (prec) numSize += 1; // for the '.'
118-
// avoiding Stack smashing protect failure!
119-
maxPrec = width - numSize;
120-
if (prec) prec = maxPrec > 0 ? maxPrec : 0;
121-
122-
sprintf(fmt, "%%%d.%df", numSize, prec);
123-
sprintf(s, fmt, number);
124-
return s;
125-
}
126-
#else
127-
// orginal code from Arduino ESP8266
12891
char * dtostrf(double number, signed char width, unsigned char prec, char *s) {
12992
bool negative = false;
13093

@@ -197,4 +160,3 @@ char * dtostrf(double number, signed char width, unsigned char prec, char *s) {
197160
*out = 0;
198161
return s;
199162
}
200-
#endif

0 commit comments

Comments
 (0)