Skip to content

Commit fdda28c

Browse files
committed
Remove deprecation diagnostic supppression for dtostrf
1 parent 66aa7db commit fdda28c

File tree

2 files changed

+23
-7
lines changed

2 files changed

+23
-7
lines changed

api/deprecated-avr-comp/avr/dtostrf.c.impl

-3
Original file line numberDiff line numberDiff line change
@@ -29,12 +29,9 @@
2929
char *dtostrf (double val, signed char width, unsigned char prec, char *sout) {
3030
asm(".global _printf_float");
3131

32-
#pragma GCC diagnostic push
33-
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
3432
char fmt[20];
3533
sprintf(fmt, "%%%d.%df", width, prec);
3634
sprintf(sout, fmt, val);
3735
return sout;
38-
#pragma GCC diagnostic pop
3936
}
4037

test/src/dtostrf.cpp

+23-4
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,8 @@
66
* INCLUDE
77
**************************************************************************************/
88

9-
#include <api/deprecated-avr-comp/avr/dtostrf.h>
10-
11-
#include <stdlib.h>
9+
#include <cstdio>
10+
#include <cfloat>
1211

1312
/**************************************************************************************
1413
* FUNCTION IMPLEMENTATION
@@ -17,8 +16,28 @@
1716
#ifdef __cplusplus
1817
extern "C" {
1918
#endif
19+
/*
20+
* A fundamental issue with dtostrf is the risk of buffer overflow as the size of the
21+
* output buffer is not passed in. Previous implementation relied on sprintf which has
22+
* the same issue and has now been deprecated, leading to compilation warnings that are
23+
* considered fatal. Here, we use snprintf to avoid those warnings, with a limit
24+
* set large enough for the longest buffer used by the String class. The risk
25+
* of buffer overflow remains when a smaller buffer is passed in.
26+
*
27+
* TODO Refactor String not to rely on this function.
28+
*/
29+
char *dtostrf (double val, signed char width, unsigned char prec, char *sout) {
30+
31+
// From String.h - DOUBLE_BUF_SIZE is the largest it could use
32+
static size_t const FLT_MAX_DECIMAL_PLACES = 10;
33+
static size_t const DBL_MAX_DECIMAL_PLACES = FLT_MAX_DECIMAL_PLACES;
34+
static size_t const DOUBLE_BUF_SIZE = DBL_MAX_10_EXP + DBL_MAX_DECIMAL_PLACES + 1 /* '-' */ + 1 /* '.' */ + 1 /* '\0' */;
2035

21-
#include <api/deprecated-avr-comp/avr/dtostrf.c.impl>
36+
char fmt[20];
37+
snprintf(fmt, sizeof(fmt), "%%%d.%df", width, prec);
38+
snprintf(sout, DOUBLE_BUF_SIZE, fmt, val);
39+
return sout;
40+
}
2241

2342
#ifdef __cplusplus
2443
} // extern "C"

0 commit comments

Comments
 (0)