Skip to content

Commit 82a8ad2

Browse files
authored
Merge pull request #613 from pennam/string-fix
check boundaries converting float/double to String
2 parents 7c38f34 + b80585c commit 82a8ad2

File tree

2 files changed

+17
-2
lines changed

2 files changed

+17
-2
lines changed

cores/arduino/WString.cpp

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,14 @@
2020
*/
2121

2222
#include "WString.h"
23+
#include <float.h>
24+
25+
/*********************************************/
26+
/* Static Member Initialisation */
27+
/*********************************************/
28+
29+
size_t const String::FLT_MAX_DECIMAL_PLACES = DECIMAL_DIG;
30+
size_t const String::DBL_MAX_DECIMAL_PLACES = DECIMAL_DIG;
2331

2432
/*********************************************/
2533
/* Constructors */
@@ -107,15 +115,19 @@ String::String(unsigned long value, unsigned char base)
107115

108116
String::String(float value, unsigned char decimalPlaces)
109117
{
118+
static size_t const FLOAT_BUF_SIZE = (FLT_MAX_10_EXP + 1) + FLT_MAX_DECIMAL_PLACES + 1 /* '-' */ + 1 /* '.' */ + 1 /* '\0' */;
110119
init();
111-
char buf[33];
120+
char buf[FLOAT_BUF_SIZE];
121+
decimalPlaces = decimalPlaces < FLT_MAX_DECIMAL_PLACES ? decimalPlaces : FLT_MAX_DECIMAL_PLACES;
112122
*this = dtostrf(value, (decimalPlaces + 2), decimalPlaces, buf);
113123
}
114124

115125
String::String(double value, unsigned char decimalPlaces)
116126
{
127+
static size_t const DOUBLE_BUF_SIZE = (DBL_MAX_10_EXP + 1) + DBL_MAX_DECIMAL_PLACES + 1 /* '-' */ + 1 /* '.' */ + 1 /* '\0' */;
117128
init();
118-
char buf[33];
129+
char buf[DOUBLE_BUF_SIZE];
130+
decimalPlaces = decimalPlaces < DBL_MAX_DECIMAL_PLACES ? decimalPlaces : DBL_MAX_DECIMAL_PLACES;
119131
*this = dtostrf(value, (decimalPlaces + 2), decimalPlaces, buf);
120132
}
121133

cores/arduino/WString.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,9 @@ class String
5050
typedef void (String::*StringIfHelperType)() const;
5151
void StringIfHelper() const {}
5252

53+
static size_t const FLT_MAX_DECIMAL_PLACES;
54+
static size_t const DBL_MAX_DECIMAL_PLACES;
55+
5356
public:
5457
// constructors
5558
// creates a copy of the initial value.

0 commit comments

Comments
 (0)