From d0b041f17c34fc36fc8121cfe23e2da2b79cf4fa Mon Sep 17 00:00:00 2001 From: "Dmitrij D. Czarkoff" Date: Mon, 28 Dec 2015 11:07:41 +0100 Subject: Use realloc(3) for extending buffer It may save some CPU cycles if there is enough space to grow the array without copying memory chunks. Two side effects of the change: proper error checking added and dangerous memcpy(3) call removed. --- src/navigator.c | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/navigator.c b/src/navigator.c index ac3eac6..fcaa93a 100644 --- a/src/navigator.c +++ b/src/navigator.c @@ -46,12 +46,15 @@ void imv_navigator_destroy(struct imv_navigator *nav) static void add_item(struct imv_navigator *nav, const char *path) { if(nav->buf_size == nav->num_paths) { - int new_buf_size = nav->buf_size * 2; - char **new_paths = malloc(sizeof(char*) * new_buf_size); - memcpy(new_paths, nav->paths, sizeof(char*) * nav->buf_size); - free(nav->paths); + char **new_paths; + nav->buf_size *= 2; + new_paths = realloc(nav->paths, sizeof(char*) * nav->buf_size); + if (new_paths == NULL) { + perror("add_item"); + free(nav->paths); + exit(1); + } nav->paths = new_paths; - nav->buf_size = new_buf_size; } nav->paths[nav->num_paths] = strdup(path); nav->num_paths += 1; -- cgit v1.2.3