Skip to content

Commit

Permalink
addItemToItemList
Browse files Browse the repository at this point in the history
Improve realloc function to speed up. Can still be improved
  • Loading branch information
tnut committed Apr 4, 2024
1 parent 42d1ee9 commit 3d2e6f7
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 7 deletions.
19 changes: 12 additions & 7 deletions src/string_utils.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -40,19 +40,24 @@ itemList *initItemList(void)
{
itemList *list = (itemList*)Malloc(sizeof *list);
list->items = (char **)Malloc(sizeof (*list->items));
list->count = 0;
list->count = 1;
list->capacity = 1;
return list;
}

void addItemToItemList(itemList *list, const char *item)
{
char **realloc_tmp;
realloc_tmp = (char **)realloc( list->items, sizeof *list->items * (list->count + 1) );
if ( realloc_tmp == NULL ) {
return;
if ( list->capacity == list->count) {
char **realloc_tmp;
list->capacity = list->count * 2;
realloc_tmp = (char **)realloc( list->items, sizeof *list->items * list->capacity );
if ( realloc_tmp == NULL ) {
printf("Cannot reallocate realloc_tmp: %d", &realloc_tmp);
return;
}
list->items = realloc_tmp;
}
list->items = realloc_tmp;
list->items[ list->count ] = strdup(item);
list->items[ list->count - 1 ] = strdup(item);
++list->count;
}

Expand Down
2 changes: 2 additions & 0 deletions src/string_utils.h
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ typedef struct
{
char **items;
unsigned int count;
unsigned int capacity;
} itemList;

/**
Expand Down Expand Up @@ -111,6 +112,7 @@ std::string stripWhiteSpace(const std::string& s);
std::vector<std::string> parseDelimitedVectorList
(const std::string& s, const char *delimiter);

/* populate a vector of string with a delimited character */
const std::vector<std::string> parseDelimitedVectorList
(const std::string& s, const char& c);

Expand Down

0 comments on commit 3d2e6f7

Please sign in to comment.