From 84aacc55d1332a92f64757518c5524cfc82f12f3 Mon Sep 17 00:00:00 2001 From: Bartosz Golaszewski Date: Sat, 1 Jul 2017 14:11:40 +0200 Subject: [PATCH] chip: lazily allocate lines Only allocate the array of line pointers is they're actually needed. Signed-off-by: Bartosz Golaszewski --- src/lib/chip.c | 29 ++++++++++++++++------------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/src/lib/chip.c b/src/lib/chip.c index 093fe90..3c90b8e 100644 --- a/src/lib/chip.c +++ b/src/lib/chip.c @@ -58,13 +58,6 @@ struct gpiod_chip * gpiod_chip_open(const char *path) return NULL; } - chip->lines = calloc(chip->cinfo.lines, sizeof(struct gpiod_line *)); - if (!chip->lines) { - close(chip->fd); - free(chip); - return NULL; - } - return chip; } @@ -148,20 +141,23 @@ void gpiod_chip_close(struct gpiod_chip *chip) struct gpiod_line *line; unsigned int i; - for (i = 0; i < chip->cinfo.lines; i++) { - line = chip->lines[i]; + if (chip->lines) { + for (i = 0; i < chip->cinfo.lines; i++) { + line = chip->lines[i]; - if (line) { - gpiod_line_release(line); - line_free(line); + if (line) { + gpiod_line_release(line); + line_free(line); + } } + + free(chip->lines); } if (chip->chip_ctx) line_chip_ctx_free(chip->chip_ctx); close(chip->fd); - free(chip->lines); free(chip); } @@ -191,6 +187,13 @@ gpiod_chip_get_line(struct gpiod_chip *chip, unsigned int offset) return NULL; } + if (!chip->lines) { + chip->lines = calloc(chip->cinfo.lines, + sizeof(struct gpiod_line *)); + if (!chip->lines) + return NULL; + } + if (!chip->chip_ctx) { chip->chip_ctx = line_chip_ctx_new(chip, chip->fd); if (!chip->chip_ctx) -- 2.30.2