"strtok" is considered not-safe. You can find more details about it here:
Why is strtok() Considered Unsafe?
So instead of using strtok, you can simply replace '/'s with '\0's and then use 'strdup' to split the path. You can find the implementation below:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char **split(char *path, int *size)
{
char *tmp;
char **splitted = NULL;
int i, length;
if (!path){
goto Exit;
}
tmp = strdup(path);
length = strlen(tmp);
*size = 1;
for (i = 0; i < length; i++) {
if (tmp[i] == '/') {
tmp[i] = '\0';
(*size)++;
}
}
splitted = (char **)malloc(*size * sizeof(*splitted));
if (!splitted) {
free(tmp);
goto Exit;
}
for (i = 0; i < *size; i++) {
splitted[i] = strdup(tmp);
tmp += strlen(splitted[i]) + 1;
}
return splitted;
Exit:
*size = 0;
return NULL;
}
int main()
{
int size, i;
char **splitted;
splitted = split("foo/foobar/file.txt", &size);
for (i = 0; i < size; i++) {
printf("%d: %s\n", i + 1, splitted[i]);
}
// TODO: free splitted
return 0;
}
Note that much better implementations exists, which iterates on the path only once and use "realloc"s to allocate more memory to the pointers when necessary.