From efab2914d7669f1b443867d2f2d859b218ed0aad Mon Sep 17 00:00:00 2001 From: Matthieu Schaller <matthieu.schaller@durham.ac.uk> Date: Mon, 7 Dec 2015 15:02:49 +0000 Subject: [PATCH] Safer addlink from Pedro's branch --- src/engine.c | 11 ++++++++--- src/engine.h | 2 +- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/src/engine.c b/src/engine.c index e21e476cc3..3f7bfc8156 100644 --- a/src/engine.c +++ b/src/engine.c @@ -69,7 +69,11 @@ int engine_rank; struct link *engine_addlink(struct engine *e, struct link *l, struct task *t) { - struct link *res = &e->links[atomic_inc(&e->nr_links)]; + const int ind = atomic_inc(&e->nr_links); + if (ind >= e->size_links) { + error("Link table overflow."); + } + struct link *res = &e->links[ind]; res->next = l; res->t = t; return res; @@ -1058,8 +1062,9 @@ void engine_maketasks(struct engine *e) { /* Allocate the list of cell-task links. The maximum number of links is the number of cells (s->tot_cells) times the number of neighbours (27) times the number of interaction types (2, density and force). */ - if (e->links != NULL) free(e->links); - if ((e->links = malloc(sizeof(struct link) * s->tot_cells * 27 * 2)) == NULL) + free(e->links); + e->size_links = s->tot_cells * 27 * 2; + if ((e->links = malloc(sizeof(struct link) * e->size_links)) == NULL) error("Failed to allocate cell-task links."); e->nr_links = 0; diff --git a/src/engine.h b/src/engine.h index 7c8f03d381..025dc219af 100644 --- a/src/engine.h +++ b/src/engine.h @@ -128,7 +128,7 @@ struct engine { /* Linked list for cell-task association. */ struct link *links; - int nr_links; + int nr_links, size_links; }; /* Function prototypes. */ -- GitLab