Skip to content

Commit 1a6a417

Browse files
committed
check boundaries converting float/double to String
1 parent 87faf93 commit 1a6a417

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

cores/arduino/WString.cpp

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,13 @@
2121

2222
#include "WString.h"
2323

24+
/*********************************************/
25+
/* Static Member Initialisation */
26+
/*********************************************/
27+
28+
size_t const String::FLT_MAX_DECIMAL_PLACES;
29+
size_t const String::DBL_MAX_DECIMAL_PLACES;
30+
2431
/*********************************************/
2532
/* Constructors */
2633
/*********************************************/
@@ -107,15 +114,19 @@ String::String(unsigned long value, unsigned char base)
107114

108115
String::String(float value, unsigned char decimalPlaces)
109116
{
117+
static size_t const FLOAT_BUF_SIZE = 38 + FLT_MAX_DECIMAL_PLACES + 1 /* '-' */ + 1 /* '.' */ + 1 /* '\0' */;
110118
init();
111-
char buf[33];
119+
char buf[FLOAT_BUF_SIZE];
120+
decimalPlaces = decimalPlaces < FLT_MAX_DECIMAL_PLACES ? decimalPlaces : FLT_MAX_DECIMAL_PLACES;
112121
*this = dtostrf(value, (decimalPlaces + 2), decimalPlaces, buf);
113122
}
114123

115124
String::String(double value, unsigned char decimalPlaces)
116125
{
126+
static size_t const DOUBLE_BUF_SIZE = 38 + DBL_MAX_DECIMAL_PLACES + 1 /* '-' */ + 1 /* '.' */ + 1 /* '\0' */;
117127
init();
118-
char buf[33];
128+
char buf[DOUBLE_BUF_SIZE];
129+
decimalPlaces = decimalPlaces < DBL_MAX_DECIMAL_PLACES ? decimalPlaces : DBL_MAX_DECIMAL_PLACES;
119130
*this = dtostrf(value, (decimalPlaces + 2), decimalPlaces, buf);
120131
}
121132

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 = 10;
54+
static size_t const DBL_MAX_DECIMAL_PLACES = FLT_MAX_DECIMAL_PLACES;
55+
5356
public:
5457
// constructors
5558
// creates a copy of the initial value.

0 commit comments

Comments
 (0)