Fixes String(float) issue with Stack Smashing (#6138)

Fixes #5873
This commit is contained in:
Rodrigo Garcia
2022-01-17 09:44:49 -03:00
committed by GitHub
parent caef4006af
commit 841599c248
4 changed files with 23 additions and 11 deletions

View File

@ -112,16 +112,28 @@ String::String(unsigned long value, unsigned char base) {
*this = buf;
}
String::String(float value, unsigned char decimalPlaces) {
String::String(float value, unsigned int decimalPlaces) {
init();
char buf[33];
char *buf = (char*)malloc(decimalPlaces + 42);
if (buf) {
*this = dtostrf(value, (decimalPlaces + 2), decimalPlaces, buf);
free(buf);
} else {
*this = "nan";
log_e("No enought memory for the operation.");
}
}
String::String(double value, unsigned char decimalPlaces) {
String::String(double value, unsigned int decimalPlaces) {
init();
char buf[33];
char *buf = (char*)malloc(decimalPlaces + 312);
if (buf) {
*this = dtostrf(value, (decimalPlaces + 2), decimalPlaces, buf);
free(buf);
} else {
*this = "nan";
log_e("No enought memory for the operation.");
}
}
String::~String() {

View File

@ -71,8 +71,8 @@ class String {
explicit String(unsigned int, unsigned char base = 10);
explicit String(long, unsigned char base = 10);
explicit String(unsigned long, unsigned char base = 10);
explicit String(float, unsigned char decimalPlaces = 2);
explicit String(double, unsigned char decimalPlaces = 2);
explicit String(float, unsigned int decimalPlaces = 2);
explicit String(double, unsigned int decimalPlaces = 2);
~String(void);
// memory management

View File

@ -88,7 +88,7 @@ char* ultoa(unsigned long value, char* result, int base) {
return result;
}
char * dtostrf(double number, signed char width, unsigned char prec, char *s) {
char * dtostrf(double number, signed int width, unsigned int prec, char *s) {
bool negative = false;
if (isnan(number)) {
@ -117,7 +117,7 @@ char * dtostrf(double number, signed char width, unsigned char prec, char *s) {
// Round correctly so that print(1.999, 2) prints as "2.00"
// I optimized out most of the divisions
double rounding = 2.0;
for (uint8_t i = 0; i < prec; ++i)
for (uint32_t i = 0; i < prec; ++i)
rounding *= 10.0;
rounding = 1.0 / rounding;

View File

@ -39,7 +39,7 @@ char* utoa (unsigned int val, char *s, int radix);
char* ultoa (unsigned long val, char *s, int radix);
char* dtostrf (double val, signed char width, unsigned char prec, char *s);
char* dtostrf (double val, signed int width, unsigned int prec, char *s);
#ifdef __cplusplus
} // extern "C"