change the way string arrays are initialized

This commit is contained in:
Chris Cromer 2021-07-16 13:35:29 -04:00
parent 1b68196f16
commit e548acdb8a
3 changed files with 25 additions and 27 deletions

View File

@ -19,11 +19,13 @@
/** /**
* Create a String Array by initializing its structure. * Create a String Array by initializing its structure.
* @param string_array The String Array to create. * @return Returns a new String Array.
*/ */
void create_string_array(StringArray *string_array) { StringArray *create_string_array() {
StringArray *string_array = malloc(sizeof(StringArray));
string_array->array = NULL; string_array->array = NULL;
string_array->size = 0; string_array->size = 0;
return string_array;
} }
/** /**
@ -93,12 +95,6 @@ void delete_string_array(StringArray *string_array, int index) {
* @param string_array The String Array to free. * @param string_array The String Array to free.
*/ */
void free_string_array(StringArray *string_array) { void free_string_array(StringArray *string_array) {
if (string_array->array == NULL) {
fprintf(stderr, "StringArray is not freeable!\n");
free_string_array(string_array);
exit(EXIT_FAILURE);
}
else {
for (size_t i = 0; i < string_array->size; i++) { for (size_t i = 0; i < string_array->size; i++) {
if (string_array->array[i] != NULL) { if (string_array->array[i] != NULL) {
free(string_array->array[i]); free(string_array->array[i]);
@ -110,5 +106,8 @@ void free_string_array(StringArray *string_array) {
string_array->array = NULL; string_array->array = NULL;
} }
string_array->size = 0; string_array->size = 0;
if (string_array != NULL) {
free(string_array);
string_array = NULL;
} }
} }

View File

@ -27,7 +27,7 @@ typedef struct {
size_t size; size_t size;
} CleanArray; } CleanArray;
void create_string_array(StringArray *string_array); StringArray *create_string_array();
void insert_string_array(StringArray *string_array, char *string); void insert_string_array(StringArray *string_array, char *string);

View File

@ -64,13 +64,12 @@ void loop() {
char *line = get_console_input(); char *line = get_console_input();
StringArray args; StringArray *args = create_string_array();
create_string_array(&args);
char *saveptr = NULL; char *saveptr = NULL;
char *token = strtok_r(line, " ", &saveptr); char *token = strtok_r(line, " ", &saveptr);
while (token) { while (token) {
insert_string_array(&args, token); insert_string_array(args, token);
token = strtok_r(NULL, " ", &saveptr); token = strtok_r(NULL, " ", &saveptr);
} }
if (line != NULL) { if (line != NULL) {
@ -79,17 +78,17 @@ void loop() {
} }
// The user didn't type anything so restart the loop // The user didn't type anything so restart the loop
if (args.size == 0) { if (args->size == 0) {
continue; continue;
} }
if (is_builtin(args.array[0])) { if (is_builtin(args->array[0])) {
run_builtin(&args); run_builtin(args);
} }
else { else {
launch_program(&args); launch_program(args);
} }
free_string_array(&args); free_string_array(args);
} }
} }