| 24 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
24 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 25 */ |
25 */ |
| 26 |
26 |
| 27 #include "string_list.h" |
27 #include "string_list.h" |
| 28 |
28 |
| |
29 #include <assert.h> |
| |
30 |
| 29 string_list_t* new_string_list_t() { |
31 string_list_t* new_string_list_t() { |
| 30 string_list_t* stringList = malloc(sizeof(string_list_t)); |
32 string_list_t* stringList = malloc(sizeof(string_list_t)); |
| 31 stringList->count = 0; |
33 stringList->count = 0; |
| 32 stringList->items = NULL; |
34 stringList->capacity = 32; |
| |
35 stringList->items = calloc(sizeof(char*), stringList->capacity); |
| 33 |
36 |
| 34 return stringList; |
37 return stringList; |
| 35 } |
38 } |
| 36 |
39 |
| 37 void destroy_string_list_t(string_list_t* list) { |
40 void destroy_string_list_t(string_list_t* list) { |
| 46 /* Adds an item to the list, if a NULL-list is specified, the item will |
49 /* Adds an item to the list, if a NULL-list is specified, the item will |
| 47 * be freed. This way a NULL-list can be used as garbage bin. |
50 * be freed. This way a NULL-list can be used as garbage bin. |
| 48 */ |
51 */ |
| 49 void add_string(string_list_t* list, char* item) { |
52 void add_string(string_list_t* list, char* item) { |
| 50 if (list) { |
53 if (list) { |
| |
54 if (list->count < list->capacity) { |
| |
55 list->items[list->count++] = item; |
| |
56 return; |
| |
57 } |
| |
58 size_t newCapacity = list->capacity * 2; |
| 51 char** reallocated_list = |
59 char** reallocated_list = |
| 52 realloc(list->items, sizeof(char*) * (list->count + 1)); |
60 realloc(list->items, sizeof(char*) * newCapacity); |
| 53 if (reallocated_list != NULL) { |
61 assert(reallocated_list != NULL); |
| 54 list->items = reallocated_list; |
62 list->capacity = newCapacity; |
| 55 list->items[list->count] = item; |
63 list->items = reallocated_list; |
| 56 list->count++; |
64 list->items[list->count++] = item; |
| 57 } |
|
| 58 } else { |
65 } else { |
| 59 free(item); |
66 free(item); |
| 60 } |
67 } |
| 61 } |
68 } |
| 62 |
69 |