From 6c3f8259e9dd5d30e27e214d363a5eef0760a479 Mon Sep 17 00:00:00 2001 From: Chris Cromer Date: Fri, 16 Jul 2021 14:16:53 -0400 Subject: [PATCH] make StringArrays NULL terminated --- src/array.c | 16 +++++++++++++--- src/launch.c | 14 ++++---------- 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/src/array.c b/src/array.c index cf60ace..0c2bbed 100644 --- a/src/array.c +++ b/src/array.c @@ -23,6 +23,10 @@ */ StringArray *create_string_array() { StringArray *string_array = malloc(sizeof(StringArray)); + if (string_array == NULL) { + perror("malloc"); + exit(EXIT_FAILURE); + } string_array->array = NULL; string_array->size = 0; return string_array; @@ -35,25 +39,30 @@ StringArray *create_string_array() { */ void insert_string_array(StringArray *string_array, char *string) { if (string_array->size == 0) { - string_array->array = malloc(sizeof(char *)); + string_array->array = malloc(2 * sizeof(char *)); if (string_array->array == NULL) { perror("malloc"); + free_string_array(string_array); exit(EXIT_FAILURE); } } else { - string_array->array = realloc(string_array->array, (string_array->size + 1) * sizeof(char *)); + string_array->array = realloc(string_array->array, (string_array->size + 2) * sizeof(char *)); if (string_array->array == NULL) { perror("realloc"); + free_string_array(string_array); exit(EXIT_FAILURE); } } string_array->array[string_array->size] = malloc(sizeof(string)); if (string_array->array == NULL) { perror("malloc"); + free_string_array(string_array); exit(EXIT_FAILURE); } strcpy(string_array->array[string_array->size], string); + // A NULL terminated array + string_array->array[string_array->size + 1] = NULL; string_array->size++; } @@ -76,9 +85,10 @@ void delete_string_array(StringArray *string_array, int index) { } free(string_array->array[string_array->size - 1]); string_array->array[string_array->size - 1] = NULL; - string_array->array = realloc(string_array->array, (string_array->size - 1) * sizeof(char *)); + string_array->array = realloc(string_array->array, (string_array->size) * sizeof(char *)); if (string_array->array == NULL) { perror("realloc"); + free_string_array(string_array); exit(EXIT_FAILURE); } string_array->size--; diff --git a/src/launch.c b/src/launch.c index 128c07b..00b8938 100644 --- a/src/launch.c +++ b/src/launch.c @@ -30,17 +30,11 @@ void launch_program(StringArray *args) { child = fork(); if (child == 0) { - // Copy the array and add a NULL to the end of it - char *argv[args->size + 1]; - for (size_t i = 0; i < args->size; i++) { - argv[i] = args->array[i]; + if (execvp(args->array[0], args->array) == -1) { + fprintf(stderr, "%s: command not found\n", args->array[0]); + free_string_array(args); + exit(EXIT_FAILURE); } - argv[args->size] = NULL; - - execvp(args->array[0], argv); - fprintf(stderr, "%s: command not found\n", args->array[0]); - free_string_array(args); - exit(EXIT_FAILURE); } else if (child < 0) { perror("fork");