Introduction
Introduction Statistics Contact Development Disclaimer Help
tuse portable reallocarray instead of calloc when appending grains - granular -…
git clone git://src.adamsgaard.dk/granular
Log
Files
Refs
README
LICENSE
---
commit 422756f899e08157157233654041678a5512b9e5
parent cb1a16972c2a61f0229980932fe3e451ba53d22d
Author: Anders Damsgaard <[email protected]>
Date: Thu, 25 Mar 2021 17:39:25 +0100
use portable reallocarray instead of calloc when appending grains
Diffstat:
M simulation.c | 9 ++-------
M util.c | 18 ++++++++++++++++++
M util.h | 2 ++
3 files changed, 22 insertions(+), 7 deletions(-)
---
diff --git a/simulation.c b/simulation.c
t@@ -46,13 +46,8 @@ sim_free(struct simulation *sim)
void
sim_add_grain(struct simulation *sim, struct grain *g)
{
- struct grain *tmp = NULL;
-
- if (!(tmp = calloc(sim->np + 1, sizeof(*g))))
- err(1, "%s: sim.grains calloc", __func__);
- memcpy(tmp, sim->grains, sim->np * sizeof(*g));
- free(sim->grains);
- sim->grains = tmp;
+ if (!(sim->grains = xreallocarray(sim->grains, sim->np + 1, sizeof(*g)…
+ err(1, "%s: sim.grains reallocarray", __func__);
sim->grains[sim->np++] = *g;
}
diff --git a/util.c b/util.c
t@@ -1,6 +1,7 @@
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
+#include <err.h>
#include "granular.h"
void
t@@ -105,3 +106,20 @@ random_value_powerlaw(double min, double max)
return pow((pow(max, power + 1.0) - pow(min, power + 1.0)) * randomval…
+ pow(min, power + 1.0), 1.0 / (power + 1.0));
}
+
+void *
+xreallocarray(void *m, size_t n, size_t s)
+{
+ void *nm;
+
+ if (n == 0 || s == 0) {
+ free(m);
+ return NULL;
+ }
+ if (s && n > (size_t) - 1 / s)
+ err(1, "realloc: overflow");
+ if (!(nm = realloc(m, n * s)))
+ err(1, "realloc");
+
+ return nm;
+}
diff --git a/util.h b/util.h
t@@ -15,4 +15,6 @@ double residual(const double new_val, const double old_val);
double random_value_uniform(double min, double max);
double random_value_powerlaw(double power, double min, double max);
+void * xreallocarray(void *m, size_t n, size_t s);
+
#endif
You are viewing proxied material from mx1.adamsgaard.dk. The copyright of proxied material belongs to its original authors. Any comments or complaints in relation to proxied material should be directed to the original authors of the content concerned. Please see the disclaimer for more details.