Skip to content

Commit 1d700bf

Browse files
AMDmi3oetiker
authored andcommitted
Fix UB when calculating median of all-NaN values
The current code contains undefined behavior where all-NaN values are passed to median. In that case we end up with final_elements==0 in the following branch: else { rpnstack->s[++stptr] = 0.5 * (element_ptr[final_elements / 2] + element_ptr[final_elements / 2 - 1]); } and so we use 0 and -1 as element_ptr array indexes. The latter is ill-formed and leads to a crash in my case. Move the check which accounts for the last NaN earlier, so we could push NaN and finish right away.
1 parent bfe03f3 commit 1d700bf

File tree

1 file changed

+6
-5
lines changed

1 file changed

+6
-5
lines changed

src/rrd_rpncalc.c

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1253,16 +1253,17 @@ short rpn_calc(
12531253
}
12541254
}
12551255

1256+
/* when goodvals and badvals meet, they might have met on a
1257+
* NAN, which wouldn't decrease final_elements. so, check
1258+
* that now. */
1259+
if (isnan(*goodvals))
1260+
--final_elements;
1261+
12561262
stptr -= elements;
12571263
if (!final_elements) {
12581264
/* no non-NAN elements; push NAN */
12591265
rpnstack->s[++stptr] = DNAN;
12601266
} else {
1261-
/* when goodvals and badvals meet, they might have met on a
1262-
* NAN, which wouldn't decrease final_elements. so, check
1263-
* that now. */
1264-
if (isnan(*goodvals))
1265-
--final_elements;
12661267
/* and finally, take the median of the remaining non-NAN
12671268
* elements. */
12681269
qsort(element_ptr, final_elements, sizeof(double),

0 commit comments

Comments
 (0)