add memory cleanup at exit

This commit is contained in:
Chris Cromer 2021-07-06 23:47:19 -04:00
parent fd4fd05f2c
commit cc153bd481
2 changed files with 34 additions and 0 deletions

View File

@ -22,6 +22,11 @@ typedef struct {
size_t size; size_t size;
} StringArray; } StringArray;
typedef struct {
void **array;
size_t size;
} CleanArray;
void create_string_array(StringArray *string_array); void create_string_array(StringArray *string_array);
void insert_string_array(StringArray *string_array, char *string); void insert_string_array(StringArray *string_array, char *string);

View File

@ -22,10 +22,39 @@
#include "console_line.h" #include "console_line.h"
#include "launch.h" #include "launch.h"
static CleanArray clean;
/**
* Add memory address to array to be cleaned up later.
* @param data The data to be cleaned up on exit.
*/
void add_to_cleanup(void *data) {
clean.array = realloc(clean.array, (clean.size + 1) * sizeof(void *));
clean.array[clean.size++] = data;
}
/**
* Cleanup memory when exiting.
*/
void exit_cleanup() {
for (size_t i = 0; i < clean.size; i++) {
if (clean.array[i] != NULL) {
free(clean.array[i]);
clean.array[i] = NULL;
}
}
if (clean.array != NULL) {
free(clean.array);
clean.array = NULL;
}
}
/** /**
* This is the loop that checks for user input and acts on it. * This is the loop that checks for user input and acts on it.
*/ */
void loop() { void loop() {
clean.size = 0;
atexit(exit_cleanup);
while (1) { while (1) {
print_input_line(); print_input_line();