From e000c605b0d81066edb6b715dc0be6222d2bf9e0 Mon Sep 17 00:00:00 2001 From: Joshua Ulrich Date: Sun, 22 Aug 2021 08:34:55 -0500 Subject: [PATCH] Check number of non-NA obs before loop calculation The example below would segfault because 'x' has fewer non-NA obs than the value for 'n' in runPercentRank(). x <- data.frame(y = c(rep(NA, 5), 1:5)) runPercentRank(x, 6, FALSE) Thanks to Ian Fellows for the report. Fixes #112. --- src/percent_rank.c | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/src/percent_rank.c b/src/percent_rank.c index 1f97b97..cf58391 100644 --- a/src/percent_rank.c +++ b/src/percent_rank.c @@ -59,16 +59,18 @@ SEXP ttr_rollPercentRank(SEXP _x, SEXP _n, SEXP _cumul, SEXP _mult) /* Find first non-NA input value */ int beg = n - 1; - for (i = 0; i <= beg; i++) { + int n_na = 0; + for (i = 0; i < beg; i++) { + /* first 'n' observations are set to NA */ + d_result[i] = NA_REAL; /* Account for leading NAs in input */ if (ISNA(d_x[i])) { - d_result[i] = NA_REAL; beg++; - continue; - } - /* Set leading NAs in output */ - if (i < beg) { - d_result[i] = NA_REAL; + n_na++; + if (beg >= nr) { + error("runPercentRank input has %d rows, %d NA. Cannot calculate result with n = %d.", + nr, n_na, n); + } } }