Skip to content

Commit

Permalink
Use malloc() over variable-length array (#6270)
Browse files Browse the repository at this point in the history
* Use malloc() over variable-length array

* Cast to get the format specifier right

* combine error handling

* extra careful to possibly free() one if only one failed to allocate

* double-free(), consistent with elsewhere
  • Loading branch information
MichaelChirico authored Jul 16, 2024
1 parent bca0d3e commit 6cc6d53
Showing 1 changed file with 7 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/fsort.c
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,12 @@ SEXP fsort(SEXP x, SEXP verboseArg) {
// and ii) for small vectors with just one batch

t[1] = wallclock();
double mins[nBatch], maxs[nBatch];
double *mins = (double *)malloc(nBatch * sizeof(double));
double *maxs = (double *)malloc(nBatch * sizeof(double));
if (!mins || !maxs) {
free(mins); free(maxs);
error(_("Failed to allocate %d bytes in fsort()."), (int)(2 * nBatch * sizeof(double)));
}
const double *restrict xp = REAL(x);
#pragma omp parallel for schedule(dynamic) num_threads(getDTthreads(nBatch, false))
for (int batch=0; batch<nBatch; ++batch) {
Expand All @@ -149,6 +154,7 @@ SEXP fsort(SEXP x, SEXP verboseArg) {
if (mins[i]<min) min=mins[i];
if (maxs[i]>max) max=maxs[i];
}
free(mins); free(maxs);
if (verbose) Rprintf(_("Range = [%g,%g]\n"), min, max);
if (min < 0.0) error(_("Cannot yet handle negatives."));
// TODO: -0ULL should allow negatives
Expand Down

0 comments on commit 6cc6d53

Please sign in to comment.