Skip to content

Commit

Permalink
Check number of non-NA obs before loop calculation
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
joshuaulrich committed Aug 22, 2021
1 parent 0fbb7ba commit e000c60
Showing 1 changed file with 9 additions and 7 deletions.
16 changes: 9 additions & 7 deletions src/percent_rank.c
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
}

Expand Down

0 comments on commit e000c60

Please sign in to comment.