#include #include "track_list.h" // the maximum number of tracks allowed const int INITIAL_TRACKS_CAPACITY = 10; void track_list_init(track_list *l) { l->starts = malloc(sizeof(int) * INITIAL_TRACKS_CAPACITY); l->ends = malloc(sizeof(int) * INITIAL_TRACKS_CAPACITY); if (l->starts != NULL && l->ends != NULL) { // mallocs were successful l->capacity = INITIAL_TRACKS_CAPACITY; } else { // allocation failure; free whichever was allocated (safe to free(NULL)) free(l->starts); l->starts = NULL; free(l->ends); l->ends = NULL; l->capacity = 0; // and we ought to let the caller know something went wrong here } l->count = 0; } void track_list_add(track_list *l, int start, int end) { // error checking on parameters if (l == NULL || (l->count > 0 && start < l->ends[l->count - 1]) || start > end) { return; } if (l->count == l->capacity) { int new_capacity = l->capacity == 0 ? 1 : l->capacity * 2; // make new, bigger arrays int *bigger_starts = malloc(sizeof(int) * new_capacity); int *bigger_ends = malloc(sizeof(int) * new_capacity); // make sure there was space available for those bigger arrays if (bigger_starts != NULL && bigger_ends != NULL) { // copy from the old, too-small arrays into the new, bigger ones for (int i = 0; i < l->capacity; i++) { bigger_starts[i] = l->starts[i]; bigger_ends[i] = l->ends[i]; } // free the old, too-small arrays free(l->starts); free(l->ends); // save pointers to the new, bigger arrays l->starts = bigger_starts; l->ends = bigger_ends; l->capacity = new_capacity; } else { // memory allocation was unsuccessful free(bigger_starts); free(bigger_ends); } } if (l->count < l->capacity) { // we will get here unless the mallocs in the resizing case failed l->starts[l->count] = start; l->ends[l->count] = end; l->count++; } else { // fail silently? // maybe we can do better than that, eh? } } void track_list_destroy(track_list *l) { if (l != NULL) { // free arrays free(l->starts); free(l->ends); // zero out so subsequent operations on the destroyed track list // won't cause problems l->capacity = 0; l->count = 0; } }