tarrays.c: check return from memory allocations and exit on errors - granular - granular dynamics simulation
(HTM) git clone git://src.adamsgaard.dk/granular
(DIR) Log
(DIR) Files
(DIR) Refs
(DIR) README
(DIR) LICENSE
---
(DIR) commit 1c5cb83233d982f7110258f1ef54fdc422c70cff
(DIR) parent 2411376bd4ea88e2184dce638984407b56208f9a
(HTM) Author: Anders Damsgaard <anders@adamsgaard.dk>
Date: Thu, 18 Mar 2021 14:37:38 +0100
arrays.c: check return from memory allocations and exit on errors
Diffstat:
M arrays.c | 19 +++++++++++++------
1 file changed, 13 insertions(+), 6 deletions(-)
---
(DIR) diff --git a/arrays.c b/arrays.c
t@@ -1,6 +1,7 @@
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
+#include <err.h>
#define DEG2RAD(x) (x*M_PI/180.0)
t@@ -72,7 +73,8 @@ linspace(const double lower, const double upper, const int n)
double dx;
check_magnitude(__func__, 1, n);
- x = malloc(n * sizeof(double));
+ if (!(x = calloc(n, sizeof(double))))
+ err(1, "%s: x calloc", __func__);
dx = (upper - lower) / (double) (n - 1);
for (i = 0; i < n; ++i)
x[i] = lower + dx * i;
t@@ -88,7 +90,8 @@ spacing(const double *x, const int n)
double *dx;
check_magnitude(__func__, 2, n);
- dx = malloc((n - 1) * sizeof(double));
+ if (!(dx = calloc((n - 1), sizeof(double))))
+ err(1, "%s: dx calloc", __func__);
for (i = 0; i < n - 1; ++i)
dx[i] = x[i + 1] - x[i];
t@@ -103,7 +106,8 @@ zeros(const int n)
double *x;
check_magnitude(__func__, 1, n);
- x = malloc(n * sizeof(double));
+ if (!(x = malloc(n * sizeof(double))))
+ err(1, "%s: x calloc", __func__);
for (i = 0; i < n; ++i)
x[i] = 0.0;
t@@ -118,7 +122,8 @@ ones(const int n)
double *x;
check_magnitude(__func__, 1, n);
- x = malloc(n * sizeof(double));
+ if (!(x = calloc(n, sizeof(double))))
+ err(1, "%s: x calloc", __func__);
for (i = 0; i < n; ++i)
x[i] = 1.0;
t@@ -133,7 +138,8 @@ initval(const double value, const int n)
double *x;
check_magnitude(__func__, 1, n);
- x = malloc(n * sizeof(double));
+ if (!(x = calloc(n, sizeof(double))))
+ err(1, "%s: x calloc", __func__);
for (i = 0; i < n; ++i)
x[i] = value;
t@@ -278,7 +284,8 @@ normalize(const double *in, const int n)
double *out;
check_magnitude(__func__, 1, n);
- out = malloc(n * sizeof(double));
+ if (!(out = calloc(n, sizeof(double))))
+ err(1, "%s: out calloc", __func__);
copy_values(in, out, n);
max_val = max(out, n);