aboutsummaryrefslogtreecommitdiff
path: root/src/str.c
diff options
context:
space:
mode:
authorJoseph Hunkeler <jhunkeler@gmail.com>2023-10-31 12:07:52 -0400
committerJoseph Hunkeler <jhunkeler@gmail.com>2023-10-31 12:07:52 -0400
commitaa023f04838b571afc9d1891450373a840ad1dfe (patch)
tree588161f8cbee5ce38829bfa9daedca864bd57102 /src/str.c
parenta3f18180ea3a5aa15f75623637152800424ce8fd (diff)
downloadstasis-aa023f04838b571afc9d1891450373a840ad1dfe.tar.gz
Fixes maximum number of tokens parsed by split() function
* Resets the string pointer before returning to avoid freeing the wrong address in memory
Diffstat (limited to 'src/str.c')
-rw-r--r--src/str.c21
1 files changed, 12 insertions, 9 deletions
diff --git a/src/str.c b/src/str.c
index 8a5a43a..c9c6767 100644
--- a/src/str.c
+++ b/src/str.c
@@ -187,6 +187,7 @@ char** split(char *_sptr, const char* delim, size_t max)
// Duplicate the input string and save a copy of the pointer to be freed later
char *orig = _sptr;
char *sptr = strdup(orig);
+ char *sptr_begin = sptr;
if (!sptr) {
return NULL;
@@ -216,25 +217,27 @@ char** split(char *_sptr, const char* delim, size_t max)
// Separate the string into individual parts and store them in the result array
int i = 0;
+ size_t x = max;
char *token = NULL;
while((token = strsep(&sptr, delim)) != NULL) {
- if (max && i > max) {
- --i;
- strcat(result[i], delim);
- strcat(result[i], token);
+ result[i] = calloc(BUFSIZ, sizeof(char));
+ if (x < max) {
+ strcat(result[i], strstr(orig, delim) + 1);
+ break;
} else {
- result[i] = calloc(BUFSIZ, sizeof(char));
if (!result[i]) {
- free(sptr);
+ free(sptr_begin);
return NULL;
}
strcpy(result[i], token);
- i++; // next record
}
+ i++;
+ --x;
//memcpy(result[i], token, strlen(token) + 1); // copy the string contents into the record
}
- //free(orig);
- free(sptr);
+ free(sptr_begin);
+ sptr_begin = NULL;
+ sptr = NULL;
return result;
}